Example #1
0
 protected void AddState(FiniteState state, IEnumerable <Production> productions)
 {
     foreach (var production in productions)
     {
         AddState(state, production);
     }
 }
    void takeFiniteStates()
    {
        Component [] _finiteStatesTemp = myGameObject.GetComponents(typeof(FiniteState));

        myFiniteStatesNames = new string[_finiteStatesTemp.Length - 1];
        myFiniteStates      = new FiniteState[_finiteStatesTemp.Length - 1];

        int realIndex = 0;

        for (int index = 0; index < _finiteStatesTemp.Length; index++)
        {
            FiniteState finst = (FiniteState)_finiteStatesTemp[realIndex];

            if (finst.stateName != myStateName)
            {
                myFiniteStates[realIndex]      = finst;
                myFiniteStatesNames[realIndex] = finst.stateName;

                realIndex++;
            }


            //Debug.Log ("componente : " + co.name);
        }
    }
Example #3
0
 /// <summary>
 /// Changes the state. Produces a warning if the state you are moving to does not comply with the mask of the current state, and then does nothing.
 /// </summary>
 /// <param name='stateName'>
 /// State name.
 /// </param>
 public void ChangeState(FiniteStateList stateName)
 {
     if (_currState != null)
     {
         FiniteState nextState = this[stateName.ToString()];
         if (_currState.CanTransitionToState(nextState) || _currState == nextState)
         {
             _currState.DeInit();
             _currState = this[stateName.ToString()];
             _currState.Init();
             history.Push(_currState);
             if (OnStateChangeEvent != null)
             {
                 OnStateChangeEvent();
             }
         }
         else
         {
             Debug.LogError("State \"" + _currState.name + "\" cannot transition to state \"" + nextState.name + "\". You should check your logic.");
         }
     }
     else
     {
         _currState = this[stateName.ToString()];
         _currState.Init();
         history.Push(_currState);
         history.Push(_currState);
         if (OnStateChangeEvent != null)
         {
             OnStateChangeEvent();
         }
     }
 }
Example #4
0
    public void PerformTransition(StateTransition trans)
    {
        if (trans == StateTransition.NullTransition)
        {
            return;
        }

        StateID id = _currentState.GetTargetState(trans);

        if (id == StateID.NullStateID)
        {
            return;
        }

        _currentStateID = id;
        foreach (FiniteState fs in _stateList)
        {
            if (fs.ID == _currentStateID)
            {
                _currentState.DoBeforeQuit();
                _currentState = fs;
                _currentState.DoBeforeEnter();
                break;
            }
        }
    }
Example #5
0
	/// <summary>
	/// 	Goes the previous state which was saved in the activity stack.
	/// </summary>
	public void GoToPreviousState()
	{
		//testing this out.. something like this should work.
		history.Pop();
		FiniteState lastState = history.Peek();
		ChangeState((FiniteStateList) System.Enum.Parse(typeof(FiniteStateList), lastState.name));
	}
Example #6
0
    void Start()
    {
        /**Gets called by unity when the script is initialized
         * */

        //initialization
        mainState          = FiniteState.Still;
        attackState        = AttackState.InPosition;
        targetWayPointType = WayPoint.ambush;

        enemyMovement = GetComponent <EnemyMovement> ();
        character     = GetComponent <EnemyCharacter>();
        agent         = gameObject.GetComponent <NavMeshAgent> ();
        logicTime     = delta_LogicTime;
        visionTime    = delta_VisionTime;
        threatSpottedeltaTimeimeOut = deltaTime_ThreatSpottedTimemeOut;
        threat              = null;
        dir                 = Vector3.zero;
        ambushTimeOut       = 0.0f;
        delta_AmbushTimeOut = 2.0f;
        delta_MotionTimeOut = 8.0f;
        motionTimeOut       = time + delta_MotionTimeOut;
        tactics             = RoundManager.AITactics;
        rand                = new System.Random();
    }
Example #7
0
    public TransitionHFSM(string checkMethod, string checkMethodScript, GameObject checkMethodGameObject, FiniteState target)
    {
        checkFunc           = checkMethod;
        checkFuncScript     = checkMethodScript;
        checkFuncGameObject = checkMethodGameObject;

        targetState = target;
    }
    /// <summary>
    /// Add a new transition from 1 state to another.
    /// </summary>
    public ITransitionCommand AddTransition(FiniteState fromState, System.Type transition_type, FiniteState toState)
    {
        // Components should only be instantiated by a game object, which is why AddTransition
        // takes a transition_type as an argument and not a fully instantiated component.

        ITransitionCommand component = gameObject.AddComponent(transition_type) as ITransitionCommand;
        return AddTransition(fromState,component,toState);
    }
Example #9
0
            public Graph(FiniteState state, Automata <TInstruction, TOperand> automata)
            {
                State    = state;
                Automata = automata;

                BeginNode  = new BeginStateNode(Automata, this);
                ReturnNode = new ReturnStateNode(Automata, this);
            }
 void AddStateWindow(FiniteState state)
 {
     StateWindow wnd = new StateWindow();
     state.WindowRect.width = Mathf.Clamp(state.WindowRect.width,150,Mathf.Infinity);
     state.WindowRect.height = Mathf.Clamp(state.WindowRect.height,100,Mathf.Infinity);
     wnd.state = state;
     StateWindowMap.Add(state,wnd);
     StateWindows.Add(wnd);
 }
Example #11
0
 public Human()
 {
     hunger         = 100;
     hungerTick     = 0.05f;
     currentState   = new FiniteState();
     nextHungerTick = Time.time + hungerTick;
     stateName      = currentState.ToString();
     hungry         = false;
     ID             = -1;
 }
Example #12
0
 protected SubGraph(Automata <TInstruction, TOperand> automata, FiniteState state, Graph invokingGraph) : base(state)
 {
     Automata = automata;
     automata.RegisterSubGraph(this);
     Graph         = automata.EnsureGraph(state);
     InvokingGraph = invokingGraph;
     EnterNode     = new EnterStateNode(automata, invokingGraph, this);
     LeaveNode     = new LeaveStateNode(automata, invokingGraph, this);
     DfaBarrier    = Graph.DfaBarrier;
 }
Example #13
0
        //Very INCOMPLETE class; finish: epsilon closure, concat/union/star/dot/single

        //Remember, graphs are immutable (builders); FiniteStates are too (empty)
        public NFA(Graph <FiniteState, char> states, FiniteState startState, HashSet <FiniteState> finalStates)
        {
            this.states     = states ?? throw new ArgumentNullException(nameof(states));
            this.startState = startState ?? throw new ArgumentNullException(nameof(startState));
            if (finalStates == null)
            {
                throw new ArgumentNullException(nameof(finalStates));
            }
            this.finalStates = new HashSet <FiniteState>(finalStates);
        }
    public override void OnInspectorGUI()
    {
        FiniteState obj = target as FiniteState;

        EditorGUILayout.LabelField("Name : ");

        obj.stateName = EditorGUILayout.TextField(obj.stateName);

        myStateName = obj.stateName;

        //myGameObject = EditorGUILayout.ObjectField ("Obj : ", myGameObject, typeof(GameObject), true) as GameObject;

        takeMyMethods();

        myGameObject = EditorGUILayout.ObjectField("Obj : ", myGameObject, typeof(GameObject), true) as GameObject;

        if (myGameObject != null)
        {
            prova = EditorGUILayout.Foldout(prova, "State Methods");

            if (prova)
            {
                obj.initializeFunc = fillInitializeMethod(obj, "Initilize");

                obj.updateFunc = fillStateMethod(obj, "Update");
            }

            transitionSize = EditorGUILayout.IntField("Transitions ", transitionSize);

            if (transitionSize > 0)
            {
                obj.transitions = new TransitionHFSM[transitionSize];

                takeFiniteStates();

                for (int i = 0; i < transitionSize; i++)
                {
                    foldOut[i] = EditorGUILayout.Foldout(foldOut[i], "N." + i);

                    if (foldOut[i])
                    {
                        string checkMeth = "";
                        string targetS   = "";

                        checkMeth = EditorGUILayout.TextField(checkMeth);

                        targetS = fillFiniteStateField(obj, i);
                        //checkMeth = fillMethodField(obj, "Transition");
                        //targetS;
                    }
                }
            }
        }
    }
Example #15
0
        public LucPacScripted()
            : base("LucPacScripted")
        {
            _currentAgentState  = FiniteState.Wander;
            _previousAgentState = _currentAgentState;
            _testStats          = new TestStats();

            #region State Initialization
            _states.Add(FiniteState.Wander, new State()
            {
                Action    = this.Wander,
                OnSuspend = this.Wander_OnSuspend,
                OnBegin   = this.Wander_OnBegin
            });
            _states.Add(FiniteState.Ambush, new State()
            {
                Action    = this.Ambush,
                OnSuspend = this.Ambush_OnSuspend,
                OnBegin   = this.Ambush_OnBegin
            });
            _states.Add(FiniteState.EndGame, new State()
            {
                Action    = EndGame,
                OnSuspend = EndGame_OnSuspend,
                OnBegin   = EndGame_OnBegin
            });
            _states.Add(FiniteState.Hunt, new State()
            {
                Action    = Hunt,
                OnSuspend = Hunt_OnSuspend,
                OnBegin   = Hunt_OnBegin
            });
            _states.Add(FiniteState.Flee, new State()
            {
                Action    = Flee,
                OnSuspend = Flee_OnSuspend,
                OnBegin   = Flee_OnBegin
            });
            #endregion

            // Create the session ID that will be used for testing
            this._testSessionId       = GenerateSessionID();
            this._testStats.SessionID = _testSessionId;

            // Create the directory that the data is going to be stored in
            _testDataFolder   = Directory.CreateDirectory(Environment.CurrentDirectory + string.Format("/{0}", _testSessionId));
            _testImagesFolder = _testDataFolder.CreateSubdirectory("images");
            _testLogFolder    = _testDataFolder.CreateSubdirectory("logs");

            instance = this;

            _roundDuration.Start();
            _stopWatch.Start();
        }
Example #16
0
            public EntryPointSubGraph(Automata <TInstruction, TOperand> automata, FiniteState state) : base(automata, state, null)
            {
                InitNode = new InitStateNode(automata, this);
                EndNode  = new EndStateNode(automata, this);

                InitNode.OutEdges.Add(new Edge(InitNode, EnterNode));
                LeaveNode.OutEdges.Add(new Edge(LeaveNode, EndNode));
                EndPath = new ExecutionPath(LeaveNode, new Node[] { EndNode }, -1);
                Automata.RegisterExecutionPath(EndPath);

                //EndNode.EnsureReady();
            }
        public void TestAddOneTransition()
        {
            FiniteState gettingWorkItem = new FiniteState("GettingWorkItem");
            FiniteState movingToErrors  = new FiniteState("MovingToErrors");

            FiniteStateEvent actionFailed = new FiniteStateEvent("ActionFailed");

            gettingWorkItem.AddTransition(actionFailed, movingToErrors);

            Assert.That(gettingWorkItem.Transitions.Count, Is.EqualTo(1));
            Assert.That(gettingWorkItem.Transitions.ContainsKey("ActionFailed"));
        }
        public void TestAddState()
        {
            FiniteStateMachine fsm = new FiniteStateMachine("Turnstile");
            FiniteState        movingToProcessed = new FiniteState("MovingToProcessed")
            {
                OnEnterAction = () => { }
            };

            FiniteState addedState = fsm.AddState(movingToProcessed);

            Assert.That(addedState, Is.EqualTo(movingToProcessed));
        }
Example #19
0
        public LucPacScripted()
            : base("LucPacScripted")
        {
            m_CurrentState     = FiniteState.Wander;
            m_PreviousFSMState = m_CurrentState;

            // Initiate a new object of the test stats.
            m_TestStats = new TestStats();

            #region State Initialization
            /// States that are involved.
            m_States.Add(FiniteState.Wander, new State()
            {
                Action    = this.Wander,
                OnSuspend = this.Wander_OnSuspend,
                OnBegin   = this.Wander_OnBegin
            });
            m_States.Add(FiniteState.Ambush, new State()
            {
                Action    = this.Ambush,
                OnSuspend = this.Ambush_OnSuspend,
                OnBegin   = this.Ambush_OnBegin
            });
            m_States.Add(FiniteState.EndGame, new State()
            {
                Action    = EndGame,
                OnSuspend = EndGame_OnSuspend,
                OnBegin   = EndGame_OnBegin
            });
            m_States.Add(FiniteState.Hunt, new State()
            {
                Action    = Hunt,
                OnSuspend = Hunt_OnSuspend,
                OnBegin   = Hunt_OnBegin
            });
            m_States.Add(FiniteState.Flee, new State()
            {
                Action    = Flee,
                OnSuspend = Flee_OnSuspend,
                OnBegin   = Flee_OnBegin
            });
            #endregion

            // Create the session ID that will be used for testing
            this.m_TestSessionID       = GenerateSessionID();
            this.m_TestStats.SessionID = m_TestSessionID;

            instance = this;

            m_RoundDuration.Start();
            m_Stopwatch.Start();
        }
Example #20
0
	/// <summary>
	/// Unity method. 
	/// </summary>
	void Start()
	{
		InitializeStates();
		_currState = defaultState;
		if(_states.Count == 0)
		{
			Debug.LogError("No states!");
			return;
		}

		if(autoInit) 
			_currState.Init();
	}
Example #21
0
    public void AddStateTransition(STATE stateID, EVENT inputEvent, STATE outputStateID)
    {
        FiniteState <EVENT, STATE> State;

        if (!mapState.TryGetValue(stateID, out State))
        {
            //  만일 동일한 State가 존재하지 않는다면 새로 생성한다.
            State = new FiniteState <EVENT, STATE>(stateID);
            mapState.Add(stateID, State);
        }
        //  상태 전이 정보를 추가한다.
        State.AddTransition(inputEvent, outputStateID);
    }
        public void TestAddDuplicateTransition()
        {
            FiniteState gettingWorkItem   = new FiniteState("GettingWorkItem");
            FiniteState movingToErrors    = new FiniteState("MovingToErrors");
            FiniteState movingToProcessed = new FiniteState("MovingToProcessed");

            FiniteStateEvent actionSucceeded = new FiniteStateEvent("ActionSucceeded");

            Assert.That(() => {
                gettingWorkItem.AddTransition(actionSucceeded, movingToProcessed);
                gettingWorkItem.AddTransition(actionSucceeded, movingToErrors);
            }, Throws.InstanceOf <ArgumentException>().And.Message.EqualTo($"Duplicate event name='{actionSucceeded.Name}' used to create a transition from state name='{gettingWorkItem.Name}'."));
        }
Example #23
0
        public static void Test()
        {
            FiniteStateMachine <Monster> monsterStateMachine = new FiniteStateMachine <Monster>(new MonsterStateProcesser <Monster>(), new MonsterOnStateChangeProcess <Monster>());
            FiniteState <Monster>        wait = monsterStateMachine.AddState(Monster.STATE_WAIT);

            wait.SetStateExecutor(new MonsterWaitExecutor <Monster>());
            FiniteState <Monster> battle = monsterStateMachine.AddState(Monster.STATE_BATTLE);

            battle.SetStateExecutor(new MonsterBattleExecutor <Monster>());
            FiniteState <Monster> charse = monsterStateMachine.AddState(Monster.STATE_CHARSE);

            charse.SetStateExecutor(new MonsterCharseExecutor <Monster>());
            monsterStateMachine.setDefaultState(wait);

            // 待机>战斗
            // 存在目标
            FiniteStateTransaction <Monster> wait2Battle = monsterStateMachine.AddTranscation(wait, battle);

            wait2Battle.AddCondition(new BoolCondition(Monster.KEY_TARGET_EXIST, true));

            // 追击>战斗
            // 和目标的距离小于攻击距离
            FiniteStateTransaction <Monster> move2Battle = monsterStateMachine.AddTranscation(charse, battle);

            move2Battle.AddCondition(new IntCondition(Monster.KET_DISTANCE, IntCondition.SMALLER, Monster.ATTACK_RANGE));

            // 追击>待机
            // 目标死亡
            FiniteStateTransaction <Monster> move2Wait = monsterStateMachine.AddTranscation(charse, wait);

            move2Wait.AddCondition(new BoolCondition(Monster.KEY_TARGET_DEAD, true));

            // 战斗>移动
            // 和目标的距离大于攻击距离
            FiniteStateTransaction <Monster> battle2Move = monsterStateMachine.AddTranscation(battle, charse);

            battle2Move.AddCondition(new IntCondition(Monster.KET_DISTANCE, IntCondition.LARGER, Monster.ATTACK_RANGE));

            // 战斗>待机
            // 目标死亡
            FiniteStateTransaction <Monster> battle2Wait = monsterStateMachine.AddTranscation(battle, wait);

            battle2Wait.AddCondition(new BoolCondition(Monster.KEY_TARGET_DEAD, true));

            Monster m = new Monster();

            for (int i = 0; i < 10; i++)
            {
                monsterStateMachine.Tick(m, 0, 0);
            }
        }
Example #24
0
	/// <summary>
	/// Adds the state.
	/// </summary>
	/// <param name='stateName'>
	/// State name.
	/// </param>
	/// <exception cref='System.Exception'>
	/// Throws an error if the maximum number of states (31) is exceeded.
	/// </exception>
	public void InitializeStates()
	{
		if(_states.Count == 0) 
			_defaultState = 0;

		foreach(FiniteStateList stateList in System.Enum.GetValues(typeof(FiniteStateList)))
		{
			FiniteState s = new FiniteState(stateList.ToString(), (int) stateList);
			_states.Add(s);
			_stateKeys.Add(stateList.ToString());
		}
		if(OnFSMInitializedEvent != null)
			OnFSMInitializedEvent();
	}	
        void DrawStates()
        {
            bool click = Event.current.type == EventType.MouseDown && Event.current.button == 0;

            if (click)
            {
                interceptedState = -1;
                repaint          = true;
            }
            for (int i = 0; i < m_StateCopys.Length; i++)
            {
                FiniteState state = m_StateCopys[i];
                bool        act;
                if (Application.isPlaying && fsmImpl.IsFSMActive)
                {
                    act = fsmImpl == null ? false : fsmImpl.CurrentStateName == state.m_StateName;
                }
                else
                {
                    act = false;
                }
                Rect rect = stateRects[i];
                rect.position -= stateViewPos - stateClipRectCenter;
                if (click && rect.Contains(Event.current.mousePosition))
                {
                    interceptedState = i;
                    interaceptPos    = new Vector2(10, 10);
                }
                bool   inter = i == interceptedState;
                string style;
                if (act)
                {
                    style = inter ? "flow node 3 on" : "flow node 3";
                }
                else if (state.m_IsDefaultState)
                {
                    style = inter ? "flow node 2 on" : "flow node 2";
                }
                else
                {
                    style = inter ? "flow node 1 on" : "flow node 1";
                }
                GUI.Label(rect, "", style);
                Installizer.contentContent.text           = state.m_StateName;
                Installizer.contentStyle.normal.textColor = Color.white;
                Installizer.contentStyle.fontSize         = Mathf.Max(1, (int)((rect.height - 10) * cellScale));
                Installizer.contentStyle.alignment        = TextAnchor.MiddleCenter;
                GUI.Label(rect, Installizer.contentContent, Installizer.contentStyle);
            }
        }
Example #26
0
 private bool TryGetNextStateByEventName(
     FiniteStateTransition transition, string eventName, out FiniteState state)
 {
     state = null;
     if (CurrentState == null || !CurrentState.Name.Equals(transition.LastStateName))
     {
         return(false);
     }
     if (!eventName.Equals(transition.EventName))
     {
         return(false);
     }
     return(allStates_.TryGetValue(transition.NextStateName, out state));
 }
        public void TestAddDuplicateState()
        {
            FiniteStateMachineEngine engine = new FiniteStateMachineEngine("Turnstile");
            FiniteState movingToProcessed   = new FiniteState("MovingToProcessed")
            {
                OnEnterAction = () => { }
            };

            Assert.That(() =>
            {
                FiniteState addedState = engine.AddState(movingToProcessed);
                addedState             = engine.AddState(movingToProcessed);
            }, Throws.InstanceOf <ArgumentException>().And.Message.EqualTo($"Attempt to add a duplicate state '{movingToProcessed.Name}'."));
        }
        public void TestAddState()
        {
            FiniteStateMachineEngine engine = new FiniteStateMachineEngine("Turnstile");
            FiniteState movingToProcessed   = new FiniteState("MovingToProcessed")
            {
                OnEnterAction = () => { }
            };

            FiniteState addedState = engine.AddState(movingToProcessed);

            Assert.That(addedState, Is.EqualTo(movingToProcessed));
            Assert.That(engine.ManagedStates.Count, Is.EqualTo(1));
            Assert.That(engine.ManagedStates.ContainsKey(movingToProcessed.Name));
        }
Example #29
0
        private EntryPointSubGraph EnsureSubGraph(FiniteState finiteState)
        {
            var subGraph = SubGraphDictionary.GetValueOrDefault(finiteState);

            if (subGraph != null)
            {
                return(subGraph);
            }

            subGraph = SubGraphDictionary[finiteState] = new EntryPointSubGraph(this, finiteState);

            subGraph.BuildExecutionGraph();

            return(subGraph);
        }
        public void TestStart()
        {
            FiniteStateMachine fsm             = new FiniteStateMachine("Turnstile");
            FiniteState        gettingWorkItem = new FiniteState("GettingWorkItem")
            {
                OnEnterAction = () => { }
            };
            FiniteState movingToProcessed = new FiniteState("MovingToProcessed")
            {
                OnEnterAction = () => { }
            };
            FiniteState addedState = fsm.AddState(gettingWorkItem);

            fsm.Start(gettingWorkItem);
            //fsm.Stop();
        }
 /// <summary>
 /// Add a new state
 /// </summary>
 /// <param name='cache'>
 /// If true, state is stored in the StateCache for serialization
 /// </param>
 public void AddState(FiniteState state, bool cache)
 {
     if(!state){
         //Debug.Log("Couldn't add state, null");
         return;
     }
     if(!TransitionMap.ContainsKey(state)){
         TransitionMap.Add(state,new List<ITransitionCommand>());
         //Debug.Log("Adding state: " + state.UniqueID);
         if(cache) {
             StateTransitionState sts = new StateTransitionState();//ScriptableObject.CreateInstance<StateTransitionState>() as StateTransitionState;
             sts.StartState = state;
             StateCache.Add(sts);
         }
     }
 }
    string fillStateMethod(FiniteState obj, string fieldName)
    {
        int index = 0;

        try {
            index = metodi
                    .Select((v, i) => new { Name = v, Index = i })
                    .First(x => x.Name == obj.updateFunc)
                    .Index;
        } catch {
            index = 0;
        }

        EditorGUILayout.LabelField("Initilize");

        return(metodi [EditorGUILayout.Popup(index, metodi)]);
    }
    static void DebugClickTimedToggle(FiniteStateMachine fsm)
    {
        FiniteState start_state =  new FiniteState();//ScriptableObject.CreateInstance<FiniteState>();
        FiniteState red_state =  new FiniteState();//ScriptableObject.CreateInstance<FiniteState>();
        FiniteState green_state =  new FiniteState();//ScriptableObject.CreateInstance<FiniteState>();
        start_state.StateName = "Start";
        red_state.StateName = "Red";
        green_state.StateName = "Green";

        {
            red_state.EnterAction = fsm.gameObject.AddComponent<StateActions.SA_ChangeColor>() as IStateAction;
            StateActions.SA_ChangeColor sa = red_state.EnterAction as StateActions.SA_ChangeColor;
            sa.NewColor = Color.red;
        }

        {
            green_state.EnterAction = fsm.gameObject.AddComponent<StateActions.SA_ChangeColor>() as IStateAction;
            StateActions.SA_ChangeColor sa = green_state.EnterAction as StateActions.SA_ChangeColor;
            sa.NewColor = Color.green;
        }

        {
            Transitions.OnMouseClick t = fsm.AddTransition(start_state,typeof(Transitions.OnMouseClick),red_state) as Transitions.OnMouseClick;
            t.Name = "click_start";

        }

        {
            Transitions.OnMouseClick t = fsm.AddTransition(red_state,typeof(Transitions.OnMouseClick),green_state) as Transitions.OnMouseClick;
            t.Name = "click_red";

        }

        {
            Transitions.OnMouseClick t = fsm.AddTransition(green_state,typeof(Transitions.OnMouseClick),red_state) as Transitions.OnMouseClick;
            t.Name = "click_green";

        }
        {
            Transitions.OnTimer2 t = fsm.AddTransition(green_state,typeof(Transitions.OnTimer2),red_state) as Transitions.OnTimer2;
            t.Name = "click_green";

            t.Delay = 2;
        }
        fsm.ChangeState(start_state);
    }
    //prende i vari componenti/script dell'oggetto
    void updateComponents(FiniteState obj)
    {
        //Component []componenti = obj.ciao.GetComponents(typeof(provainvoco));
        Component [] componenti = myGameObject.GetComponents(typeof(MonoBehaviour));

        componentiNomi = new string[componenti.Length];

        int index = 0;

        foreach (Component co in componenti)
        {
            Type tipo = co.GetType();
            componentiNomi[index] = tipo.ToString();
            index++;
            //Debug.Log ("componente : " + co.name);
        }
    }
    /// <summary>
    /// Add a new transition from 1 state to another
    /// </summary>
    /// <returns>
    public ITransitionCommand AddTransition(FiniteState fromState, ITransitionCommand component, FiniteState toState)
    {
        component.enabled = false;
        component.FSM = this;

        StateTransition st = new StateTransition(fromState,component);
        //Debug.Log("Adding new transition type " + component.GetType() + " from state " + fromState.StateName + " to state " + toState.StateName);

        if(!MapTransition(fromState,component,toState)){
            Destroy(component);	//always delete duplicate transition components
            //Debug.Log("fromState " + fromState.StateName + " already contains a transition type " + component.GetType().ToString());
            return null;
        }
        return component;
    }
 /// <summary>
 /// Add a new state, (cache defaults true)
 /// </summary>
 public void AddState(FiniteState state)
 {
     AddState(state,true);
 }
    /// <summary>
    /// Called by 'awake()' to rebuild dictionaries, which Unity doesn't serialize
    /// </summary>
    void RebuildStateTransitionMap()
    {
        TransitionMap.Clear();
        StateTransitions.Clear();
        StartState = null;
        CurrentState = null;

        //Debug.Log("Rebuilding transition map");
        //Unity serialization doesn't work w/ Generic.Dictionary, rebuild from state list
        foreach(StateTransitionState sts in StateCache){
         			AddState(sts.StartState,false);
            AddState(sts.EndState,false);

            if(sts.StartState!=null && sts.Transition!=null) {
                StateTransition st = new StateTransition(sts.StartState,sts.Transition);
                StateTransitions.Add(st,sts.EndState);

                TransitionMap[sts.StartState].Add(sts.Transition);

                if(sts.StartState.Start == true){
                    SetStart(sts.StartState,false);
                }
            }

            if(sts.Valid()){
                //Debug.Log("Rebuilding transition from " + sts.StartState.StateName + " to " + sts.EndState.StateName);
            } else if(sts.StartState!=null && sts.EndState==null){
                //Debug.Log("Rebuilding start state w/ no end state <" + sts.StartState.StateName + ">");
            } else if(sts.StartState==null && sts.EndState!=null){
                //Debug.Log("Rebuilding end state w/ no start state <" + sts.EndState.StateName + ">");
            } else if(sts.StartState==null && sts.EndState==null && sts.Transition==null){
                //Debug.Log("Warning, disconnected transition <" + sts.Transition.Name + ">");
            }
        }
        //StateTransition st1 = new StateTransition(StateCache[0].StartState,StateCache[0].Transition);
        //StateTransition st2 = new StateTransition(StartState,StateCache[0].Transition);
        //Debug.Log("Comparison Hash.  " + st1.GetHashCode() + "==" + st2.GetHashCode());
        //Debug.Log("Comparison Equl.  " + (st1 == st2).ToString());
    }
 /// <summary>
 /// Map the transitiom from 'fromState' to 'toState'.
 /// </summary>
 /// <returns>
 /// false if there is a transition from 'fromState' matching 'transition', else true;
 /// </returns>
 bool MapTransition(FiniteState fromState, ITransitionCommand transition,FiniteState toState)
 {
     return MapTransition(fromState,transition,toState,true);
 }
    static void DebugPressurePlateLight(FiniteStateMachine fsm)
    {
        FiniteState unpressed_state =  new FiniteState();//ScriptableObject.CreateInstance<FiniteState>();
        FiniteState pressed_state =  new FiniteState();//ScriptableObject.CreateInstance<FiniteState>();

        {
            //unpressed_state.EnterAction = fsm.gameObject.AddComponent<StateActions.SA_PressurePlateLight>() as IStateAction;
            //StateActions.SA_PressurePlateLight sa = unpressed_state.EnterAction as StateActions.SA_PressurePlateLight;
            //sa.State = false;
        }

        {
            pressed_state.EnterAction = fsm.gameObject.AddComponent<StateActions.SA_PressurePlateLight>() as IStateAction;
            StateActions.SA_PressurePlateLight sa = pressed_state.EnterAction as StateActions.SA_PressurePlateLight;
            sa.State = true;
        }

        {
            Transitions.OnTriggerEnterTransition t = fsm.AddTransition(unpressed_state,typeof(Transitions.OnTriggerEnterTransition),pressed_state) as Transitions.OnTriggerEnterTransition;
            t.Name = "trigger_enter";

        }

        {
            Transitions.OnTriggerExitTransition t = fsm.AddTransition(pressed_state,typeof(Transitions.OnTriggerExitTransition),unpressed_state) as Transitions.OnTriggerExitTransition;
            t.Name = "trigger_exit";

        }
        fsm.ChangeState(unpressed_state);
    }
 public void UpdateState()
 {
     currentState = currentState.CheckState();
 }
 public StateTransition(FiniteState currentState, ITransitionCommand component)
 {
     CurrentState = currentState;
     TransitionComponent = component;
 }
		public void ThrowExceptionGivenTransitionReturnsUnregisteredState()
		{
			// Arrange
			var unregisteredState = new FiniteState(0, "Unregistered");

			this.openState.RemoveTransition(this.closeTransition);

			this.closeTransition = new FiniteStateTransition(
				2,
				"Close",
				new FiniteStateMachineTransitionReason("2", "Closed"),
				unregisteredState,
				() => unregisteredState);

			this.openState.RegisterTransition(this.closeTransition);

			// Act
			this.machine.PerformTransition(this.closeTransition);
		}
 public void initialise()
 {
     currentState = initialState;
 }
    /// <summary>
    /// Change to the next state and update the currently active transitions.
    /// </summary>
    public void ChangeState(FiniteState nextState)
    {
        if(!nextState) {
            Debug.Log("Change state ignored, nextState == null");
            return;
        }

        // disable any active transition components
        SetActiveComponentsEnabled(false);

        // apply transition logic from current state
        if(CurrentState){
            CurrentState.ExitState(gameObject);
            CurrentState.DisableStateChanges();
        }
        CurrentState = nextState;
        CurrentState.EnableStateChanges();

        // apply transition to new state
        CurrentState.EnterState(gameObject);

        // Change the transition component list to the active states transitions and enable them
        ActiveTransitionList = TransitionMap[CurrentState];
        SetActiveComponentsEnabled(true);
    }
    static void DebugPressurePlate(FiniteStateMachine fsm)
    {
        FiniteState unpressed_state =  new FiniteState();//ScriptableObject.CreateInstance<FiniteState>();
        FiniteState pressed_state =  new FiniteState();//ScriptableObject.CreateInstance<FiniteState>();

        {
            unpressed_state.EnterAction = fsm.gameObject.AddComponent<StateActions.SA_PressurePlateColor>() as IStateAction;
            StateActions.SA_PressurePlateColor sa = unpressed_state.EnterAction as StateActions.SA_PressurePlateColor;
            sa.NewColor = Color.red;
        }

        {
            pressed_state.EnterAction = fsm.gameObject.AddComponent<StateActions.SA_PressurePlateColor>() as IStateAction;
            StateActions.SA_PressurePlateColor sa = pressed_state.EnterAction as StateActions.SA_PressurePlateColor;
            sa.NewColor = Color.green;
        }

        {
            Transitions.OnTriggerEnterTransition t = fsm.AddTransition(unpressed_state,typeof(Transitions.OnTriggerEnterTransition),pressed_state) as Transitions.OnTriggerEnterTransition;
            t.Name = "trigger_enter";

        }

        {
            Transitions.OnTriggerExitTransition t = fsm.AddTransition(pressed_state,typeof(Transitions.OnTriggerExitTransition),unpressed_state) as Transitions.OnTriggerExitTransition;
            t.Name = "trigger_exit";

        }
        fsm.ChangeState(unpressed_state);
    }
 public void SetStart(FiniteState start)
 {
     SetStart(start,true);
 }
    static void DebugTest(FiniteStateMachine fsm)
    {
        FiniteState start_state =  new FiniteState();//ScriptableObject.CreateInstance<FiniteState>();
        FiniteState red_state =  new FiniteState();//ScriptableObject.CreateInstance<FiniteState>();
        FiniteState green_state =  new FiniteState();//ScriptableObject.CreateInstance<FiniteState>();

        start_state.StateName = "Start";
        red_state.StateName = "Red";
        green_state.StateName = "Green";

        {
            red_state.EnterAction = fsm.gameObject.AddComponent<StateActions.SA_ChangeColor>() as IStateAction;
            StateActions.SA_ChangeColor sa = red_state.EnterAction as StateActions.SA_ChangeColor;
            sa.NewColor = Color.red;
        }

        {
            red_state.ExitAction = fsm.gameObject.AddComponent<StateActions.SA_SetVariable>() as IStateAction;
            StateActions.SA_SetVariable sa = red_state.ExitAction as StateActions.SA_SetVariable;
            sa.Value = new Vector3(1,2,3);
        }

        {
            green_state.EnterAction = fsm.gameObject.AddComponent<StateActions.SA_ChangeColor>() as IStateAction;
            StateActions.SA_ChangeColor sa = green_state.EnterAction as StateActions.SA_ChangeColor;
            sa.NewColor = Color.green;
        }

        {
            green_state.ExitAction = fsm.gameObject.AddComponent<StateActions.SA_SetScriptVariable>() as IStateAction;
            StateActions.SA_SetScriptVariable sa = green_state.ExitAction as StateActions.SA_SetScriptVariable;
            sa.ScriptName = "SimpleScript";
            sa.ValueName = "Position";
            sa.Value = new Vector3(42,43,44);
        }

        {
            Transitions.OnMouseClick t = fsm.AddTransition(start_state,typeof(Transitions.OnMouseClick),red_state) as Transitions.OnMouseClick;
            t.Name = "click_start";

        }

        {
            Transitions.OnMouseClick t = fsm.AddTransition(red_state,typeof(Transitions.OnMouseClick),green_state) as Transitions.OnMouseClick;
            t.Name = "click_red";

        }

        {
            Transitions.OnMouseClick t = fsm.AddTransition(green_state,typeof(Transitions.OnMouseClick),red_state) as Transitions.OnMouseClick;
            t.Name = "click_green";

        }
        fsm.ChangeState(start_state);
    }
 public void SetStart(FiniteState start,bool clear)
 {
     if(clear){
         foreach(StateTransitionState sts in StateCache){
             if(sts.StartState != null)sts.StartState.Start = false;
         }
     }
     Debug.Log("Setting Start: " + start.UniqueID);
     start.Start = true;
     StartState = start;
 }
    static void DebugToggleMultiColor(FiniteStateMachine fsm)
    {
        FiniteState start_state 	=  new FiniteState();//ScriptableObject.CreateInstance<FiniteState>();
        FiniteState red_state 		=  new FiniteState();//ScriptableObject.CreateInstance<FiniteState>();
        FiniteState green_state 	=  new FiniteState();//ScriptableObject.CreateInstance<FiniteState>();
        FiniteState blue_state 		=  new FiniteState();//ScriptableObject.CreateInstance<FiniteState>();
        FiniteState yellow_state 	=  new FiniteState();//ScriptableObject.CreateInstance<FiniteState>();
        FiniteState magenta_state 	=  new FiniteState();//ScriptableObject.CreateInstance<FiniteState>();

        start_state.StateName 	= "Start";
        red_state.StateName 		= "Red";
        green_state.StateName 	= "Green";
        blue_state.StateName 	= "blue";
        yellow_state.StateName 	= "yellow";
        magenta_state.StateName 	= "magenta";

        {
            red_state.EnterAction = fsm.gameObject.AddComponent<StateActions.SA_ChangeColor>() as IStateAction;
            StateActions.SA_ChangeColor sa = red_state.EnterAction as StateActions.SA_ChangeColor;
            sa.NewColor = Color.red;
        }

        {
            green_state.EnterAction = fsm.gameObject.AddComponent<StateActions.SA_ChangeColor>() as IStateAction;
            StateActions.SA_ChangeColor sa = green_state.EnterAction as StateActions.SA_ChangeColor;
            sa.NewColor = Color.green;
        }

        {
            blue_state.EnterAction = fsm.gameObject.AddComponent<StateActions.SA_ChangeColor>() as IStateAction;
            StateActions.SA_ChangeColor sa = blue_state.EnterAction as StateActions.SA_ChangeColor;
            sa.NewColor = Color.blue;
        }

        {
            yellow_state.EnterAction = fsm.gameObject.AddComponent<StateActions.SA_ChangeColor>() as IStateAction;
            StateActions.SA_ChangeColor sa = yellow_state.EnterAction as StateActions.SA_ChangeColor;
            sa.NewColor = Color.yellow;
        }
        {
            magenta_state.EnterAction = fsm.gameObject.AddComponent<StateActions.SA_ChangeColor>() as IStateAction;
            StateActions.SA_ChangeColor sa = magenta_state.EnterAction as StateActions.SA_ChangeColor;
            sa.NewColor = Color.magenta;
        }

        {
            Transitions.OnTimer2 t = fsm.AddTransition(start_state,typeof(Transitions.OnTimer2),red_state) as Transitions.OnTimer2;
            t.Name = "timer_start";

            t.Delay = 1.0f;
        }

        {
            Transitions.OnTimer2 t = fsm.AddTransition(red_state,typeof(Transitions.OnTimer2),green_state) as Transitions.OnTimer2;
            t.Name = "timer_red";

            t.Delay = Random.value * 10.0f;
        }
        {
            Transitions.OnTimer2 t = fsm.AddTransition(green_state,typeof(Transitions.OnTimer2),blue_state) as Transitions.OnTimer2;
            t.Name = "timer_green";

            t.Delay = Random.value * 10.0f;
        }
        {
            Transitions.OnTimer2 t = fsm.AddTransition(blue_state,typeof(Transitions.OnTimer2),yellow_state) as Transitions.OnTimer2;
            t.Name = "timer_blue";

            t.Delay = Random.value * 10.0f;
        }
        {
            Transitions.OnTimer2 t = fsm.AddTransition(yellow_state,typeof(Transitions.OnTimer2),magenta_state) as Transitions.OnTimer2;
            t.Name = "timer_yellow";

            t.Delay = Random.value * 10.0f;
        }
        {
            Transitions.OnTimer2 t = fsm.AddTransition(magenta_state,typeof(Transitions.OnTimer2),red_state) as Transitions.OnTimer2;
            t.Name = "timer_magenta";

            t.Delay = Random.value * 10.0f;
        }
        fsm.ChangeState(start_state);
    }
    /// <summary>
    /// Map the transitiom from 'fromState' to 'toState'.
    /// </summary>
    /// <returns>
    /// false if there is a transition from 'fromState' matching 'transition', else true;
    /// </returns>
    bool MapTransition(FiniteState fromState, ITransitionCommand transition,FiniteState toState,bool cache)
    {
        StateTransition st = new StateTransition(fromState,transition);
        if(StateTransitions.ContainsKey(st)){
            return false;
        }

        AddState(fromState,cache);
        AddState(toState,cache);

        StateTransitions.Add(st,toState);
        TransitionMap[fromState].Add(transition);

        if(cache){
            StateTransitionState sts = new StateTransitionState();//ScriptableObject.CreateInstance<StateTransitionState>() as StateTransitionState;
            sts.StartState = fromState;
            sts.EndState = toState;
            sts.Transition = transition;
            StateCache.Add(sts);
        }
        return true;
    }