Unity状态机

玩家状态父类代码

public class Playerstate
{
public Player pla;

public Playerstatemachine Psm;

public string statename;

public Playerstate(Player _pla, Playerstatemachine _Psm, string _statename)   //构造函数
{
    this.pla = _pla;
    this.Psm = _Psm;
    this.statename = _statename;
}

public virtual void Enter() 
{
    Debug.Log("进入状态" + statename);
}
public virtual void Update() 
{
    Debug.Log("正在状态" + statename);
}

public virtual void Exit() 
{
    Debug.Log("退出状态" + statename);
}

}

状态机代码
public class Playerstatemachine
{
public Playerstate currentstate { get; private set; }

public void initialze(Playerstate _startstate) 
{
    currentstate = _startstate;
    currentstate.Enter();
}

public void Changestate(Playerstate _nowstate) 
{
    currentstate.Exit();
    currentstate = _nowstate;
    currentstate.Enter();
}

}

玩家状态切换
public class Player : MonoBehaviour
{
public Playerstatemachine psm { get; private set; }

public playeridlestate idlestate { get; private set; }

public Playermovestate movestate { get; private set; }


private void Awake()
{
    psm = new Playerstatemachine();
    idlestate = new playeridlestate(this, psm, "idle");
    movestate = new Playermovestate(this, psm, "move");
}

private void Start()
{
    psm.initialze(idlestate);
}
private void Update()
{
    psm.currentstate.Update();
}

}

继承状态类示例
1.
public class playeridlestate : Playerstate
{
public playeridlestate(Player _pla, Playerstatemachine _Psm, string _statename) : base(_pla, _Psm, _statename)
{
}

public override void Enter()
{
    base.Enter();
}

public override void Exit()
{
    base.Exit();
}

public override void Update()
{
    base.Update();
    if (Input.GetKeyDown(KeyCode.N)) 
    {
        Psm.Changestate(pla.movestate);
    }
}

}

public class Playermovestate : Playerstate
{
public Playermovestate(Player _pla, Playerstatemachine _Psm, string _statename) : base(_pla, _Psm, _statename)
{
}

public override void Enter()
{
    base.Enter();
}

public override void Exit()
{
    base.Exit();
}

public override void Update()
{
    base.Update();
    if (Input.GetKeyDown(KeyCode.N))
    {
        Psm.Changestate(pla.idlestate);
    }
}

}

posted @ 2025-04-19 08:38  m天天  阅读(35)  评论(0)    收藏  举报