R
R
RandomProgrammer2022-01-07 16:54:41
Unity
RandomProgrammer, 2022-01-07 16:54:41

State machine implementation?

I am making a state machine for UI.
Here is the code:

namespace UI
{
    public class StateMachine
    {
        public enum States
        {
            Menu,
            Pause,
            Settings,
            GraphicsSettings,
            MusicSettings,
            GameWindow,
            NewGame,
        }

        public delegate void StateHandler(States state);
        static public event StateHandler ChangeState;

        static public States currentState
        {
            get
            {
                return currentState;
            }
            set
            {
                currentState = value;  // Здесь Unity зависает.
                ChangeState?.Invoke(value);
            }
        }
    }

    [System.Serializable]

    public class StateElement
    {
        public StateMachine.States state;
        public bool isEnabled;
    }
}

I hang this script on UI elements:
namespace UI
{
    public class UIState : MonoBehaviour
    {
        public StateElement[] states = new StateElement[System.Enum.GetValues(typeof(StateMachine.States)).Length];

        private void Awake()
        {
            StateMachine.ChangeState += (state) => ChangeState(state);
        }

        private void ChangeState(StateMachine.States state)
        {
            gameObject.SetActive(states[(int)state].isEnabled);
        }
    }
}

And in the inspector for each UI element I specify for each state whether it should be on or off. But for some reason, when setting the state, unity freezes (without "not responding"). As a result, you just have to turn it off through the task manager. Mb somewhere event looping? But it seems like there isn't. There are no errors in VS.
PS I made the class StateMachine static and now unity throws an error that the operation overflows the stack.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
RandomProgrammer, 2022-01-07
@RandomProgrammer

It turns out that setting the value in set again calls set, and so recursively.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question