Search code examples
c#unity-game-engineenumsgameobject

Enum pointing to gameobjects?


So, I have this crazy idea to have enums pointing to gameobjects.

Here's what I want to do:

/* These enums would hold gameobjects instead of ints */
enum exampleEnum{
    AddPanel,
    ListPanel
}

public class GUIManager : MonoBehaviour {
    void Start()
    {
        EnablePanel(exampleEnum.AddPanel);
    }

    void EnablePanel(GameObject panel)
    {
        panel.setActive(true);
    }
}

Is there any way to make this work? Or a workaround?

This might be possible with something other than an enum but I don't know of it if there is and I'm looking through the web for a such a solution.


Solution

  • This would satisfy your requirement, works for any amount of enum values or panels.

    // Add this to each of your panels, the enum field can be integrated into your other behaviours as well
    public class EnumPanel : MonoBehaviour 
    {
        // configurable from the Editor, the unity way.
        public ExampleEnum Type;
    }
    
    // Assign all your panles in the editor (or use FindObjectsByType<EnumPanel> in Start())
    public class GUIManager : MonoBehaviour 
    {
        // configurable from the Editor, the unity way.
        public EnumPanel[] Panels;
    
        void Start()
        {
            // Optionally find it at runtime, if assigning it via the editor is too much maintenance.
            // Panels = FindObjectsByType<EnumPanel>();
            EnablePanel(ExampleEnum.AddPanel);
        }
    
        void EnablePanel(ExampleEnum panelType)
        {
            foreach(var panel in Panels)
            {
                if(panel.Type == panelType)
                    EnablePanel(panel.gameObject);
            }
        }
    
        void EnablePanel(GameObject panel)
        {
            panel.setActive(true);
        }
    }