Finding buttons

I’m fairly new to Unity and must be missing something obvious. I need to locate all buttons on my canvas. They are all in panels or panels in panels, etc… This is to take advantage of the Layout system. I will actually use the buttons just for positioning - letting the layout system do all the heavy lifting - then inactivate each button and place my own stuff (playing cards in this case) on the canvas. I’ve got a script attached to my canvas and I’m doing this in the Start() method of the script.

So I look up how other people are saying to do this and I see lots and lots of calls to GetComponentsInChildren(). Seems simple enough but whenever I do it Unity tells me that button has to derive from Component or MonoBehavior or “be an interface”. When I check the heirarchy for Button, I see that it derives from VisualElement which derives from mscorlib.Object. I’m not sure if “be an interface” refers to some sort of object in Unity or whether it’s talking about a real C# interface. In any event, Button seems totally incompatible with GetComponents… and no variation of this I’ve tried has done anything but given me this error. So I look at GameObject.FindObjectsOfType(typeof(Button)). When I try this it complains that it only works with UnityEngine.Object derived types. Sure enough, Button derives from mscorlib.Object. These are the two methods I’ve been able to find on the web to solve the problem and neither of them seems to work. Am I missing something fundamental?

There’s got to be a way of doing this. After all, the Layout system does it obviously. Thanks for any help!

If you give each button a tag e.g: ‘button’, you could do something like this:

using UnityEngine.UI;

// Make a list to store all your buttons
    public List<Button> buttons;

    // When the game starts
    private void Start()
    {
        // Make an array of all the buttons with the tag 'button'
        GameObject[] btn = GameObject.FindGameObjectsWithTag("button");
        // Iterate through the array of 'btn' and add them to the 'buttons' list
        for (int i = 0; i < btn.Length; i++)
        {
            // Adding the current 'btn' to the 'buttons' list
            buttons.Add(btn*.GetComponent<Button>());*

}
}

// Example function making all of the buttons, non-interactable
private void MakeButtonsInactive()
{
// Iterate through each button in the ‘buttons’ list & set interactable to false
for (int i = 0; i < buttons.Count; i++)
{
buttons*.interactable = false;*
// And do what ever else you want with the buttons
}
}

You should take an array of buttons which is public and add them in inspector manually.
This is the most easy way to do this.
Second way is to take each button as private and in start you have to ***

button_name = Getcomponent();

*** which is really time consuming. :slight_smile: