Given a Panel with some number of Buttons, I’d like to have a script on that Panel that can manipulate each Button in the panel, one-by-one, in a particular way. Unfortunately, I’m having big trouble with the very first step: getting an array of Buttons.
The scripting manual says that Button is descended from MonoBehavior, which suggests you ought to be able to treat a Button as a component. So I tried this:
Button[] buttons = this.GetComponents<Button>();
Debug.Log ("buttons.length = " + buttons.Length);
but the log then tells me that buttons.Length
= 0;
The object heirarchy suggests that Buttons are GameObjects, as they have a transform, and can both be children and have children. So I tried this:
int j=0;
Button[] buttons = new Button[6];
foreach(Transform child in transform)
{
if(child.gameObject is Button)
{
buttons[j] = (Button) child.gameObject;
j++;
}
GameObject go = child.gameObject;
}
but it fails to compile. Unity warns me that the expression (child.gameObject is Button)
can never evaluate to true, and that the cast (Button) child.gameObject
is illegal.
Any advice? Within a script attached to a Panel, how can you get an array of all Buttons that are children of that Panel?