0

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.

2 Answers2

3

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));
    }
}
CodeCaster
  • 147,647
  • 23
  • 218
  • 272
  • I would also recommend storing your "activation arrays" in properties that are editable in the editor, this is usually good when you want to play around with the game's settings, i.e. `[SerializeField] private int[] _button1; [SerializeField] private int[] _button2;` – Ron May 08 '15 at 00:22
0

General answer: extract your login into methods. One example comes to my mind:

You could pass all the objects, only explicitly enable the ones you need, disable the rest.

You can have a method accept the list of objects, an array of objects you need to show and the method would loop through the objects, show the ones you need, hide the remaining ones.

Ren
  • 801
  • 1
  • 8
  • 12