- Home /
How to deactivate all GameObject in a array, except last one
RectTransform[] controls = x.GetComponentsInChildren<RectTransform>();
for (int i = 0; i < controls.Length-1 ; i++) {
controls[i].gameObject.SetActive(false);
}
here is the code.. its working perfectly.. only problem is that it isnt activating last gameobject. it is disabling all gameobjects & i dont want to disable last gameobject.
Answer by Bunny83 · Dec 25, 2020 at 10:27 AM
Just do this:
for (int i = 0; i < controls.Length ; i++) {
controls[i].gameObject.SetActive(i >= controls.Length-1);
}
Of course we have to iterate through all objects if you want to enable or disable all of them. If you don't iterate over one object, of course it won't be affected at all. The key is to use a boolean expression for the active state. Since we want to disable all objects except the last one, the condition i >= controls.Length-1
is false for all "i" except for the last one where it is true.
It didnt work! now I've changed my code a little bit here its
private GameObject[] childControls; //Childs of Parent
private GameObject Parent; //"Parent" GO
void Start() {
Parent = GameObject.FindGameObjectWithTag("GameController");
childControls = new GameObject[Parent.transform.childCount];
for (int i = 0; i < Parent.transform.childCount; i++)
{
childControls[i] = Parent.transform.GetChild(i).gameObject;
}
}
void Update (){
if (showControl)
{
for (int i = 0; i < childControls.Length; i++)
{
//childControls[30].SetActive(false);
//childControls[i-1].SetActive(false);
childControls[i].SetActive(i >= childControls.Length - 1);
}
}
}//if ends
} //update ends
but still, it didn't work!
Answer by xpath · Dec 25, 2020 at 09:34 AM
Hi, "controls.Length-1" replace with this "controls.Length-2" .I hope it works for you
yes bro I had tried that but that didn't work either
Answer by DwaneDibbley · Dec 28, 2020 at 06:10 AM
Int number = controls.length; controls[number].gameObject.SetActive(true);,Int number = controls.length; controls[number].gameObject.SetActive(true);
Answer by DwaneDibbley · Dec 25, 2020 at 01:52 PM
Int number = controls.length; controls[number].gameObject.SetActive(true);