I have the requirement to Hide and Show the specific gameobjects on specific button click.
Button-1:-
gameobject[0].SetActive(false);
gameobject[1].SetActive(false);
gameobject[2].SetActive(false);
gameobject[3].SetActive(true);
gameobject[4].SetActive(false);
gameobject[5].SetActive(false);
gameobject[6].SetActive(false);
gameobject[7].SetActive(true);
gameobject[8].SetActive(true);
Button-2:-
gameobject[0].SetActive(true);
gameobject[1].SetActive(false);
gameobject[2].SetActive(false);
gameobject[3].SetActive(false);
gameobject[4].SetActive(false);
gameobject[5].SetActive(false);
gameobject[6].SetActive(false);
gameobject[7].SetActive(true);
gameobject[8].SetActive(false);
Like these, I have some 10 buttons. It seems code is so lengthy and not efficient. Is there any way to optimize this?
Thanks.
You can assign the "indexes to activate" to an array in a button click handler, then call a method that loops over the game objects and sets their state according to whether the passed parameter contains their index:
private void Button1_Click()
{
var toActivate = new[] { 3, 7, 8 };
ActivateGameObjects(toActivate);
}
private void Button2_Click()
{
var toActivate = new[] { 0, 7 };
ActivateGameObjects(toActivate);
}
private void ActivateGameObjects(int[] toActivate)
{
for (int i = 0; i < gameobjects.Length; i++)
{
gameobjects[i].SetActive(toActivate.Contains(i));
}
}