Toggle on/off by tags

I’m currently trying to toggle objects in a tag by pressing a key. However, I’m only able to turn it off. Unable to turn it on again. May I know why is it so?

if (Input.GetKeyDown(KeyCode.F1))
        {
            list2 = GameObject.FindGameObjectsWithTag("Door");

          
if (doorC == 0)
            {
                foreach (GameObject v in list2)
                {
                    v.SetActive(false);
                }
                doorC = 1;
            }
          
            else
            {
                foreach (GameObject v in list2)
                {
                    v.SetActive(true);
                 }
                doorC = 0;
            }
            }

It’s because deactivated GameObjects aren’t returned by GameObject.Find methods. The solution is to call GameObject.FindGameObjectsWithTag(“Door”); in your Start() method and store the result once, before any of the GameObjects have been deactivated, instead of calling it every time you press a button.

1 Like

I

I see. That worked out nicely. Thank you!

1 Like