Example #1
0
        private void EnterState(State aState, object[] aArgs)
        {
#if DEBUG
            string     stateName = aState.ToString();
            bool       haveArgs  = aArgs != null;
            MethodInfo mi        = aState.GetType().GetMethod("OnEnter", BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);
            if (mi != null) // OnEnter overridden on state
            {
                bool expectsArgs = mi.GetParameters().Length > 0;

                if (!haveArgs && expectsArgs)
                {
                    Debug.Fail($"State {stateName} expects args, but none were passed in via Transition");
                }
                else if (haveArgs && !expectsArgs)
                {
                    Debug.Fail($"State {stateName} does not expect args, but some were passed in via Transition");
                }
            }
            else if (haveArgs)
            {
                Debug.Fail($"Args are being passed via Transition to State {stateName}, but State doesn't implement OnEnter(params)");
            }
#endif

            if (aArgs != null)
            {
                aState.OnEnter(aArgs);
            }
            else
            {
                aState.OnEnter();
            }
        }
    public void SetState(State s)
    {
        State old_state = current_state;

        if (s != null)
        {
            current_state = s;
        }
        else
        {
            current_state = null;
        }
        if (old_state != null)
        {
            if (old_state.OnExit != null)
            {
                old_state.OnExit();
            }
        }
        if (current_state != null)
        {
            current_state.Reset();
            if (current_state.OnEnter != null)
            {
                current_state.OnEnter();
            }
        }
    }
Example #3
0
    /// <summary>
    /// This method places new states inside the FSM,
    /// or prints an ERROR message if the state was already inside the List.
    /// First state added is also the initial state.
    /// </summary>
    public void AddState(State s)
    {
        // Check for Null reference before deleting
        if (s == null)
        {
            Debug.LogError("FSM ERROR: Null reference is not allowed");
        }

        // First State inserted is also the Initial state,
        //   the state the machine is in when the simulation begins
        if (_states.Count == 0)
        {
            _states.Add(s);
            _currentState   = s;
            _lastStateID    = StateID.eStateID_Null;
            _currentStateID = s.ID;
            _currentState.OnEnter();
            return;
        }

        // Add the state to the List if it's not inside it
        foreach (State state in _states)
        {
            if (state.ID == s.ID)
            {
                Debug.LogError("FSM ERROR: Impossible to add state " + s.ID.ToString() +
                               " because state has already been added");
                return;
            }
        }
        _states.Add(s);
    }
Example #4
0
    /// <summary>
    /// This method tries to change the state the FSM is in based on
    /// the current state and the transition passed. If current state
    ///  doesn't have a target state for the transition passed,
    /// an ERROR message is printed.
    /// </summary>
    public void PerformTransition(Transition trans)
    {
        // Check for NullTransition before changing the current state
        if (trans == Transition.eTransiton_Null)
        {
            Debug.LogError("FSM ERROR: NullTransition is not allowed for a real transition");
            return;
        }

        // Check if the currentState has the transition passed as argument
        StateID id = _currentState.GetOutputState(trans);

        if (id == StateID.eStateID_Null)
        {
            Debug.LogWarning("FSM ERROR: State " + _currentStateID.ToString() + " does not have a target state " +
                             " for transition " + trans.ToString());
            return;
        }
        // Update the currentStateID and currentState
        _currentStateID = id;
        foreach (State state in _states)
        {
            if (state.ID == _currentStateID)
            {
                // Do the post processing of the state before setting the new one
                _currentState.OnExit();
                _lastStateID  = _currentState.ID;
                _currentState = state;

                // Reset the state to its desired condition before it can reason or act
                _currentState.OnEnter();
                break;
            }
        }
    } // PerformTransition()
    void OnOperatorRecieved(char op)
    {
        if (op == '+' || op == '-' || op == '*' || op == '/' || op == '%')
        {
            if (_currentState == _waitingForOperand1)
            {
                _currentOperator.CurrentOperator = op;
                _currentState = _waitingForOperand2;
                _currentState.OnEnter();
            }
            else if (_currentState == _waitingForOperand2)
            {
                _op1.OperandData = Calculate();
                _currentState    = _waitingForOperand2;
                _currentState.OnEnter();
            }
        }

        if (op == '=')
        {
            _op1.OperandData = Calculate();
            _currentState    = _waitingForOperand1;
            _currentState.OnEnter();
        }
    }
Example #6
0
    private void SetNextState(State nextState)
    {
        currentState?.OnExit();
        nextState.OnEnter();

        currentState = nextState;
    }
Example #7
0
        private async void DoTransitionLoop()
        {
            Log.V("Transition loop started");

            while (true)
            {
                var next = _state.Next.GetResult();
                var prev = _state;

                // do transition
                _state.OnLeave();

                Log.I("Transitioning from '{0}' to '{1}'", prev, next);

                _state = next;
                if (_state == null)
                {
                    NotifyEnterDisposed();
                    break;
                }

                _state.OnEnter(prev);

                // start processing and await for the next state
                if (!_state.Process())
                {
                    break;
                }

                await _state.Next;
            }

            Log.V("Transition loop completed");
        }
Example #8
0
 public void Init(int characterId)
 {
     //初始化本对象的实时战斗信息
     this.characterId = characterId;
     //受击面向初始化
     BeAttackDir = Vector3.right;
     //初始化难度系数
     InitDegreeOfDifficulty();
     //生成实时敌人战斗信息
     RealtimeEnemyInfoConstruct();
     //状态机获取
     Animator = GetComponent <Animator>();
     //角色动画回调方法绑定
     EventCenter.Instance.SendEvent(SGEventType.AnimCallbackRigister, new EventData(null, gameObject));
     //事件中心事件注册
     RegisterEvent();
     EventCenter.Instance.RegistListener(SGEventType.BattlePauseExit, GamePauseExitListener);
     //音源获取
     AudioSource = GetComponent <AudioSource>();
     if (AudioSource == null)
     {
         AudioSource = gameObject.AddComponent <AudioSource>();
     }
     //战场player集合清空
     players.Clear();
     //将自己加入到战场敌人集合中
     BattleController.Instance.AddEnemy(this);
     //初始化当前状态类
     State = StateFactory.Instance.GetStateInstance(AIState.Idle);
     State.OnEnter(this);
     //被击打计数归0
     ContinueBeAttackCount = 0;
     //激活
     Active = BattleController.Instance.GetGameState() == GameState.Running ? true : false;
 }
Example #9
0
    private void Start()
    {
        navAgent = GetComponent <NavMeshAgent>();

        currentState = startState;
        currentState.OnEnter(this);
    }
Example #10
0
 /// <summary>
 ///The integer represents if the state you want to change is dawn (0) or dusk(1), it already checks for nullreferences
 /// </summary>
 public void SwitchState(int i, State newState)
 {
     if (i == 0)
     {
         if (dawnState != null)
         {
             dawnState.OnExit(this);
             dawnState = newState;
             dawnState.OnEnter(this);
         }
         else
         {
             dawnState = newState;
             dawnState.OnEnter(this);
         }
     }
     else
     {
         if (duskState != null)
         {
             duskState.OnExit(this);
             duskState = newState;
             duskState.OnEnter(this);
         }
         else
         {
             duskState = newState;
             duskState.OnEnter(this);
         }
     }
 }
Example #11
0
 // Handles transition to new pending state
 private void PerformPendingTransition()
 {
     if (_pendingState != null)
     {
         if (CurrentState != null)
         {
             if (_pendingState.GetType() == CurrentState.GetType())
             {
                 _pendingState = null;
             }
             else
             {
                 CurrentState.OnExit();
                 CurrentState = _pendingState;
                 CurrentState.OnEnter();
                 _pendingState = null;
             }
         }
         else
         {
             CurrentState = _pendingState;
             CurrentState.OnEnter();
             _pendingState = null;
         }
     }
 }
Example #12
0
    public void state_change_me(State current, State newstate)
    {
        int index = list.IndexOf(current);

        if (index == -1)
        {
            Debug.LogError("state_change_me(" + current + ", " + newstate + ") : " + current + " introuvable !");
            return;
        }
        while (index > 0)
        {
            index--;
            list[index].OnLeave();
        }
        current.OnLeave();
        index = list.IndexOf(current);
        if (index == -1)
        {
            Debug.LogError("state_change_son(" + current + ", " + newstate + ") : " + current + ".OnLeave() ne doit pas changer l'�tat !");
            return;
        }
        list.RemoveRange(0, index + 1);
        list.Insert(0, newstate);
        newstate.OnEnter();
        index = list.IndexOf(newstate);
        if (index != -1 && list.Count > index + 1)
        {
            list[index + 1].OnChildChanged();
        }
    }
 void Start()
 {
     if (currentState != null)
     {
         currentState.OnEnter();
     }
 }
Example #14
0
 public void TransitionToState(State nextState)
 {
     CurrentState.OnExit(this);
     nextState.OnEnter(this);
     PreviousState = CurrentState;
     CurrentState  = nextState;
 }
        private async void DoTransitionLoop(ISuccessfulCompletionSink <SubscriptionFuture> cs)
        {
            Log.V("Subscription loop started, subscription: {0}", this);
            while (true)
            {
                var next = await _state.Process();

                var prev = _state;

                // do transition
                _state.OnLeave();

                Log.I("Transitioning from '{0}' to '{1}'", prev, next);

                _state = next;
                if (next == null)
                {
                    this.NotifyDeleted();
                    break;
                }

                _state.OnEnter(prev);
            }

            cs.Succeed(Future);
            Log.V("Subscription loop completed, subscription: {0}", this);
        }
Example #16
0
 void SwitchState(State state)
 {
     _state?.OnExit();
     _state = state;
     _state.OnEnter();
     StateName = _state.GetType().Name;
 }
 public void SwithState(int type)
 {
     currentState?.OnExit();
     currentState = states[type];
     myMapMaker.myObjectPool.ReloadAssets();
     currentState?.OnEnter();
 }
Example #18
0
    /*状态改变*/
    public bool ChangeState(State state)
    {
        if (state == null)
        {
            Debug.LogError("can't find this state");

            return(false);
        }

        /*if (IsState (state.GetState ())) {
         *      return;
         * }*/

        //触发退出状态调用Exit方法
        if (mCurrentState != null)
        {
            mCurrentState.OnExit();
        }
        //保存上一个状态
        mPreviousState = mCurrentState;
        //设置新状态为当前状态
        mCurrentState = state;

        mCurrentState.SetStateMachine(this);

        //进入当前状态调用Enter方法
        mCurrentState.OnEnter();

        return(true);

        //Debug.Log ("StateMachine enter State:"+mCurrentState.GetType().ToString());
    }
Example #19
0
    private void ExitState()
    {
        if (_currentState.OnExit != null)
        {
            _currentState.OnExit();
        }

        _currentState = states [_state];

        firstCallState = true;

        Enum _previousState = _state;

        if (_currentState.OnEnter != null)
        {
            _currentState.OnEnter();
        }


        if (_state == _previousState)
        {
            updateState  = _currentState.OnUpdate != null ? _currentState.OnUpdate : EmptyMethod;
            updateState += FirstCallUpdate;
        }

        if (!_running)
        {
            inUpdate = inFixed = inLate = EmptyMethod;
        }
        else
        {
            CheckUpdateState();
        }
    }
Example #20
0
    public void SwitchState(Type newStateType)
    {
        CurrentState?.OnExit();
        CurrentState = _stateDictionary[newStateType];
        CurrentState?.OnEnter();

        // Debug.Log("State is now ["+CurrentState?.GetType()+"]");
    }
    public void ChangeState(State newState)
    {
        CurrentState.OnExit(_pluggableStateController);

        newState.OnEnter(_pluggableStateController);
        CurrentState = newState;
        // Debug.Log("Entered " + CurrentState);
    }
Example #22
0
    public virtual void ChangeState(string stateName)
    {
        State state = states[stateName];

        activeState.OnExit();
        activeState = state;
        state.OnEnter();
    }
Example #23
0
        public void IsChainable()
        {
            var state = new State("OnHold");

            Expect(state.AddHandler("foo", null), Is.EqualTo(state));
            Expect(state.OnEnter(() => {}), Is.EqualTo(state));
            Expect(state.OnExit(() => {}), Is.EqualTo(state));
        }
Example #24
0
 public void ChangeState(string toState)
 {
     if (states.ContainsKey(toState))
     {
         currentState.OnExit();
         currentState = states[toState];
         currentState.OnEnter();
     }
 }
Example #25
0
 public void SetState(State nextState)
 {
     if (currentState != null)
     {
         currentState.OnExit();
     }
     currentState = nextState;
     currentState.OnEnter(this);
 }
Example #26
0
 /// <summary>
 /// 设置敌人的AI状态
 /// </summary>
 /// <param name="state"></param>
 public void SetState(AIState state, bool restart = false)
 {
     if (state != State.GetName() || restart == true) //若想切换的状态和当前状态不一致或者前序重置,直接切换,不等到下一帧,使设状态与初始化同帧
     {
         State.OnExit(this);
         State = StateFactory.Instance.GetStateInstance(state);
         State.OnEnter(this); //直接在设置的时候就初始化
     }
 }
Example #27
0
 public void ChangeState(State toState)
 {
     if (toState != null)
     {
         currentState.OnExit();
         currentState = toState;
         currentState.OnEnter();
     }
 }
Example #28
0
        /// <summary>
        /// A static constructor in your state machine is where you define it.
        /// That way it is only ever defined once per program activation.
        ///
        /// Each transition you define takes as an argument the state machine instance (m),
        /// the state (s), the event (e) and the context (c).
        ///
        /// </summary>
        static DemoStatemachine()
        {
            UnVerified
            .OnEnter((m, s, e, c) =>
            {
                Trace.WriteLine("States can execute code when they are entered or when they are left");
                Trace.WriteLine("In this case we start a timer to bug the user until they confirm their email");
                m.Every(new TimeSpan(hours: 10, minutes: 0, seconds: 0), eScheduledCheck);

                Trace.WriteLine("You can also set a reminder to happen at a specific time, or after a given interval just once");
                m.At(new DateTime(DateTime.Now.Year + 1, 1, 1), eScheduledCheck);
                m.After(new TimeSpan(hours: 24, minutes: 0, seconds: 0), eScheduledCheck);

                Trace.WriteLine("All necessary timing information is serialized with the state machine.");
                Trace.WriteLine("The serialized state machine also exposes a property showing when it next needs to be woken up.");
                Trace.WriteLine("External code will need to call the Tick(utc) method at that time to trigger the next temporal event");

                return(Task.CompletedTask);
            })
            .When(eScheduledCheck, (m, s, e, c) =>
            {
                Trace.WriteLine("Here is where we would send a message to the user asking them to verify their email");
                // We return the current state 's' rather than 'UnVerified' in case we are in a child state of 'Unverified'
                // This makes it easy to handle hierarchical states and to either change to a different state or stay in the same state
                return(Task.FromResult(s));
            })
            .When(eUserVerifiedEmail, (m, s, e, c) =>
            {
                Trace.WriteLine("The user has verified their email address, we are done (almost)");
                // Kill the scheduled check event, we no longer need it
                m.CancelScheduledEvent(eScheduledCheck);
                // Start a timer for one last transition
                m.After(new TimeSpan(hours: 24, minutes: 0, seconds: 0), eBeenHereAWhile);
                return(Task.FromResult(VerifiedRecently));
            });

            VerifiedRecently
            .When(eBeenHereAWhile, (m, s, e, c) =>
            {
                Trace.WriteLine("User has now been a member for over 24 hours - give them additional priviledges for example");
                // No need to cancel the eBeenHereAWhile event because it wasn't auto-repeating
                //m.CancelScheduledEvent(eBeenHereAWhile);
                return(Task.FromResult(VerifiedAWhileAgo));
            });

            Verified.OnEnter((m, s, e, c) =>
            {
                Trace.WriteLine("The user is now fully verified");
                return(Task.CompletedTask);
            });

            VerifiedAWhileAgo.OnEnter((m, s, e, c) =>
            {
                Trace.WriteLine("The user has been verified for over 24 hours");
                return(Task.CompletedTask);
            });
        }
Example #29
0
 /// <summary>
 /// 强制进入某个状态
 /// </summary>
 /// <param name="state"></param>
 /// <param name="objs"></param>
 public virtual void SetActionState(State state, params object[] objs)
 {
     if (CurrActionLayerState != null)
     {
         CurrActionLayerState.OnLeave();
     }
     CurrActionLayerState = state;
     CurrActionLayerState.OnEnter(this, objs);
 }
Example #30
0
        public void AddState(Enum name, Action<Enum> enterCallback, Action updateCallback, Action<Enum> exitCallback)
        {
            State state = new State (name, enterCallback, updateCallback, exitCallback);
            this.states.Add (state.Name, state);

            if (null == this.currentState) {
                this.currentState = state;
                state.OnEnter (null);
            }
        }
Example #31
0
    protected void SetState(int stateID)
    {
        if (_curState != null)
            _curState.OnLeave(this);

        _curState = _dicStates[stateID];
        _curStateID = stateID;

        _curState.OnEnter(this);
    }
		public void MoveTo(State state) {
			if (stateStack.Count > 0) {
				var top = stateStack.Pop();
				top.OnExit();
				stateStack.Clear();
			}
			state.StateMachine = this;
			stateStack.Push(state);
			state.OnEnter();
		}
Example #33
0
    private void Start()
    {
        rb = GetComponent <Rigidbody>();

        inLockDown = false;
        currState  = new ChillState();
        currState.OnEnter(this);

        ChooseSprite();
    }
Example #34
0
    void Awake()
    {
        states = new Dictionary<System.Type, State> ();
        states.Add(typeof(FlyingState), new FlyingState(this));
        states.Add(typeof(BarrelRollLeft), new BarrelRollLeft(this));
        states.Add(typeof(BarrelRollRight), new BarrelRollRight(this));
        states.Add(typeof(TrainTransition), new TrainTransition(this));

        currentState = states[typeof(FlyingState)];
        currentState.OnEnter();
    }
Example #35
0
    /// <summary>
    /// This calls initialize on each state in the fsm. 
    /// </summary>
    protected virtual void Start()
    {
        SetStates();

        Initialize();

        foreach ( State state in states.Values )
        {
            state.Initialize(this);
        }

        currentState = states.Values.ElementAt( 0 );
        currentState.OnEnter();
    }
 public void ForceChangeToState(State newState)
 {
     currentState = newState; // Update the current state
     newState.OnEnter(); // Enter the new state
 }
 public void EnterState(State newState)
 {
     currentState.OnExit(); // Exit the current state
     currentState = newState; // Update the current state
     newState.OnEnter(); // Enter the new state
 }
Example #38
0
 public void EnterState(System.Type newStateType)
 {
     currentState.OnExit();
     currentState = states[newStateType];
     currentState.OnEnter();
 }
Example #39
0
    private bool SetStateInternal()
    {
        if(_currentState != null)
        {
            if(_currentState.OnExit != null)
            {_currentState.OnExit();}

            _currentState.ProcessLinkTo(nextState);
            _lastState = _currentState.Name;
        }

        _currentState = _stateList[nextState];
        nextState = "";
        Logger.Log(_name + " - Entering State: " + _currentState.Name, 0);

        if(_currentState != null && _currentState.OnEnter != null)
        {_currentState.OnEnter();}

        return true;
    }
Example #40
0
 public void state_change_me(State current, State newstate)
 {
     int index = list.IndexOf(current);
     if (index == -1)
     {
         Debug.LogError("state_change_me(" + current + ", " + newstate + ") : " + current + " introuvable !");
         return;
     }
     while (index > 0)
     {
         index--;
         list[index].OnLeave();
     }
     current.OnLeave();
     index = list.IndexOf(current);
     if (index == -1)
     {
         Debug.LogError("state_change_son(" + current + ", " + newstate + ") : " + current + ".OnLeave() ne doit pas changer l'�tat !");
         return;
     }
     list.RemoveRange(0, index + 1);
     list.Insert(0, newstate);
     newstate.OnEnter();
     index = list.IndexOf(newstate);
     if (index != -1 && list.Count > index + 1)
         list[index + 1].OnChildChanged();
 }
		public void PushTo(State state) {
			state.StateMachine = this;
			stateStack.Push(state);
			state.OnEnter();
		}