コード例 #1
0
    /// <summary>
    /// 这个方法为有限状态机置入新的状态
    /// 或者在该状态已经存在于列表中时打印错误信息
    /// 第一个添加的状态也是最初的状态!
    /// </summary>
    public void AddState(RoleFSMState s)
    {
        //在添加前检测空引用
        if (s == null)
        {
            Debug.LogError("FSM ERROR: Null reference is not allowed");
        }

        //被装在的第一个状态也是初始状态
        //这个状态便是状态机开始时的状态
        if (states.Count == 0)
        {
            states.Add(s);
            CurrentState   = s;
            CurrentStateID = s.ID;
            return;
        }
        //如果该状态未被添加过,则加入集合
        for (int i = 0; i < states.Count; i++)
        {
            if (states[i].ID == s.ID)
            {
                Debug.LogError("FSM ERROR: Impossible to add state " + s.ID.ToString() +
                               " because state has already been added");
                return;
            }
        }
        states.Add(s);
    }
コード例 #2
0
    /// <summary>
    /// 状态改变
    /// </summary>
    public void SwitchTransition(RoleTransition trans, Entity entity)
    {
        //在改变当前状态前检测NullTransition
        if (trans == RoleTransition.NullTransition)
        {
            Debug.LogError("FSM ERROR: NullTransition is not allowed for a real transition");
            return;
        }

        //在改变当前状态前检测当前状态是否可作为过渡的参数
        RoleStateID id = CurrentState.GetOutputState(trans);

        if (id == RoleStateID.NullStateID)
        {
            Debug.LogError("FSM ERROR: State " + CurrentStateID.ToString() + " does not have a target state " +
                           " for transition " + trans.ToString());
            return;
        }

        if (id == CurrentStateID)
        {
            //Debug.LogError("FSM ERROR:Current State is same state " + CurrentStateID.ToString());
            return;
        }

        //更新当前的状态个和状态编号
        CurrentStateID = id;
        for (int i = 0; i < states.Count; i++)
        {
            if (states[i].ID == CurrentStateID)
            {
                //离开旧状态执行方法
                CurrentState.OnExit(entity);
                CurrentState = states[i];
                //进入新的状态
                CurrentState.OnEnter(entity);
                break;
            }
        }
    }