狀態(tài)機(jī)一般情況下只有兩個類:狀態(tài)基類以及管理狀態(tài)的類第煮。
狀態(tài)機(jī)主要用于AI或者場景切換(不同場景對應(yīng)的就是游戲的不同狀態(tài)),當(dāng)然控乾,這只是本人的想法幔欧。
using UnityEngine;
using System.Collections;
public abstract class State {
public int ID { set; get; }
public Transform TargetTra { set; get; }
public StateMachine StateMac { set; get; }
public virtual void Enter() { }
public virtual void Execute() { }
public virtual void Exit() { }
}
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class StateMachine {
public Dictionary<int, State> dictionary = new Dictionary<int,State>();
public State CurrentState { set; get; }
public State GetState(int id)
{
if (dictionary.ContainsKey(id))
return dictionary[id];
else
return null;
}
public void AddState(State state)
{
int id = state.ID;
if (!dictionary.ContainsKey(id))
dictionary.Add(id, state);
}
public void RemoveState(int id)
{
if (dictionary.ContainsKey(id))
dictionary.Remove(id);
}
public void InitState(int id)
{
if (CurrentState == null)
{
CurrentState = dictionary[id];
CurrentState.Enter();
}
}
public void ChangeState(int id)
{
if (CurrentState.ID != id)
{
CurrentState.Exit();
CurrentState = dictionary[id];
CurrentState.Enter();
}
}
public void ExecuteState()
{
CurrentState.Execute();
}
public bool CheckState(int id)
{
return CurrentState.ID == id;
}
}
當(dāng)編寫具體的一個狀態(tài)時罪治,可以這樣:
using UnityEngine;
using System.Collections;
public class RotateState : State {
public RotateState(Transform targetTra, StateMachine sm)
{
ID = (int)CharacterState.rotate;
TargetTra = targetTra;
StateMac = sm;
}
public override void Enter()
{
base.Enter();
Debug.Log("進(jìn)入旋轉(zhuǎn)狀態(tài)");
TargetTra.GetComponent<MeshRenderer>().material.color = Color.green;
}
public override void Execute()
{
base.Execute();
TargetTra.transform.Rotate(Vector3.up);
}
public override void Exit()
{
base.Exit();
Debug.Log("退出旋轉(zhuǎn)狀態(tài)");
TargetTra.transform.localScale = new Vector3(2, 2, 2);
}
}
測試代碼:
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour {
StateMachine stateMachine = new StateMachine();
void Start ()
{
stateMachine.AddState(new RotateState(transform, stateMachine));
stateMachine.AddState(new RunState(transform, stateMachine));
stateMachine.InitState(((int)CharacterState.rotate));
}
void Update ()
{
stateMachine.ExecuteState();
}
void OnGUI()
{
if (GUILayout.Button("旋轉(zhuǎn)狀態(tài)"))
{
stateMachine.ChangeState((int)CharacterState.rotate);
}
if (GUILayout.Button("行走狀態(tài)"))
{
stateMachine.ChangeState((int)CharacterState.run);
}
}
}
效果圖:
文章轉(zhuǎn)自:http://blog.csdn.net/lyh916/article/details/46011715