0
votes

I just want to create an exclusive choice between some options. That's it!

But it appears to be extremely difficult with Unity Editor, so I ended-up by creating it programmatically:

    static string[] options = new string[] { "Option 0", "Option 1", "Option 2" };
    static Rect position = new Rect(0, 0, 320, 45);
    int selected = 0;

    void OnGUI()
    {
        selected = GUI.SelectionGrid(position, selected, options, options.Length, GUI.skin.toggle);
    }

But when I play, the SelectionGrid never appear in the GameObject hierarchy. Is the SelectionGrid a GameObject? Can use it with the new UI system, with useful Canvas and anchors? Any other solutions?

Thanks

1

1 Answers

2
votes

Unity legacy GUI doesn't create a GameObject on hierarchy nor a Game object for each GUI control, its concept is a little bit different of common UI based on object oriented programming.

Just for a meaning of understanding think of GUI like a state machine and each element (GUI.Button or GUI.SelectionGrid) are components that will be instantiated, positioned and handled with a single function call and you cant manipulate it as an independent object because it is more like an sub-machine or state of the GUI itself.

To control your GUI components more like objects you can approach by scripting each component or set of component and its attributes in separated MonoBehaviour classes and attach it to empty GameObjects (so you can even prefab it to reuse or instantiate progmmatically). ex:

public class MySelectionGridObject extends MonoBehaviour() {
    public Rect orientation;
    public int selectedItem;

    OnGUI() {
        selected = GUI.SelectionGrid(orientation, selected, ...);
    }
}

this way you can manipulate it by inspector or at runtime by getting the component of the gameObject instantiated, like:

MySelectionGrid grid = myGridObjectInstance.GetComponent<MySelectionGrid>(); 

my personal suggestion for you is: If you are just learning and can use Unity 5 then go for NUI (manual and lessons here) system, it simplify a lot UI construction in Unity. Go for legacy GUI (manual and references here) just if you can't upgrade your Unity to a version with NUI support or if you are working in a project already made upon legacy GUI. Independent of your choice, learn it the right way reading documentation and trying to understand how it works before start coding a lot on your project (believe me, using GUI without a good understanding of its logic can bind a huge performance issue on your project and if you create a lot of code before realize it you'll have a lot of tedious refactoring to do). Unity have a lot of video tutorial and solid documentation to follow doing examples to learn the fundamentals of the APIs ;)