- Home /
How to get an array of all Buttons attached to a Panel?
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?
Answer by tauseef_xavi · Jul 11, 2015 at 06:47 AM
Button[] buttons = this.GetComponentsInChildren<Button>();
I'd also use the optional parameter that includes inactive components:
Button[] buttons = this.GetComponentsInChildren<Button>(true);
Both great answers.
In hindsight, I see how that makes sense: $$anonymous$$y Buttons are component-type objects, and they are also children of the Panel. Thanks.
Answer by sas_88 · Jul 11, 2015 at 06:14 AM
Hi,
Follow the tutorial
https://www.youtube.com/watch?v=r1ALQCwR1Bs
Along with that,
Create a button to the panel in which size has to be displayed.
1.create a script attach it to the panel. 2.create a public gameobject and assign the button to it.
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.Events;
using UnityEngine.EventSystems;
public class Create_Button : MonoBehaviour
{
public GameObject Base;
GameObject[] Buttons=new GameObject[20];
int count=18;
void Start ()
{
cartdet ();
}
void cartdet ()
{
Buttons=new GameObject[count];
Buttons[i]=Instantiate(Base, new Vector3(0f,0f,0.0f), Quaternion.identity) as GameObject;
Buttons[i].transform.SetParent (this.transform);
Buttons[i].GetComponent<RectTransform>().localScale=new Vector3 (1f,1f,1f);
Buttons[i].name="Button"+i.ToString();
}
}
The output of the above script will looks like