Stardog

Unity State Machine Template

Aug 8th, 2013
717
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.81 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class #SCRIPTNAME# : MonoBehaviour {
  5.    
  6.     public bool bLogStateChanges;
  7.  
  8.     public enum State
  9.     {
  10.         State1,
  11.         State2
  12.     }
  13.     public State state;
  14.  
  15.     //============================================
  16.     // EVENTS
  17.     //============================================
  18.  
  19.     #region Events
  20.     public delegate void StateHandler(GameObject thisGO, State state);
  21.     public static event StateHandler StateChanged;
  22.     #endregion
  23.  
  24.     #region Event Subscriptions
  25.     void OnEnable()
  26.     {
  27.  
  28.     }
  29.     void OnDisable()
  30.     {
  31.  
  32.     }
  33.     #endregion
  34.  
  35.     //============================================
  36.     // STATES
  37.     //============================================
  38.  
  39.     #region StateFunctions
  40.     void NextState()
  41.     {
  42.         string methodName = state.ToString() + "State";
  43.         System.Reflection.MethodInfo info = GetType().GetMethod(methodName, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
  44.         StartCoroutine((IEnumerator)info.Invoke(this, null));
  45.     }
  46.     void StateEnter()
  47.     {
  48.         if (bLogStateChanges)
  49.             Debug.Log(this.GetType().Name + " / " + state + " / " + "ENTER");
  50.  
  51.         // SEND EVENT
  52.         if (StateChanged != null)
  53.             StateChanged(gameObject, state);
  54.     }
  55.     void StateExit()
  56.     {
  57.        
  58.     }
  59.     #endregion
  60.  
  61.     IEnumerator State1State()
  62.     {
  63.         StateEnter();
  64.  
  65.         while (state == State.State1)
  66.         {
  67.             yield return null;
  68.         }
  69.  
  70.         StateExit();
  71.         NextState();
  72.     }
  73.  
  74.     IEnumerator State2State()
  75.     {
  76.         StateEnter();
  77.  
  78.         while (state == State.State2)
  79.         {
  80.             yield return null;
  81.         }
  82.  
  83.         StateExit();
  84.         NextState();
  85.     }
  86.  
  87.     //============================================
  88.     // FUNCTIONS
  89.     //============================================
  90.  
  91.     void Start()
  92.     {
  93.         NextState();
  94.     }
  95.  
  96.     //============================================
  97.     // EVENT RECEIVERS
  98.     //============================================
  99.  
  100.  
  101.  
  102. }
Add Comment
Please, Sign In to add comment