Gameobject activated multiple times, possible bug..

Hi I have a script to activate and deactivate a gameobject inventoryUI with UI components.

   if(Input.GetButtonDown(Buttons.TRIANGLE)) {
        inventory = !inventory;
        inventoryUI.SetActive(inventory);
    }

inventory is a boolean var init to false. when I push the button the gameobject is activate several time generating multiple errors…

The scripts is in Update() method

Found the error, the script inventoryUI is attached to the child of InventoryUI GameObject erroneously…

What errors does it give?

For the “multiple times” issue, you have to make it so that the piece of code above doesn’t execute again unless the button is released. Otherwise, the player presses the button for several frames and makes it so that the piece of code gets executed multiple times. Look at this script.

private bool isPressed; // private field

...
void Start()
{
    ...
    isPressed = false;
    ...
}

void Update()
{
...
     if (Input.GetButtonDown(Buttons.TRIANGLE) && !isPressed)
     {

               isPressed = true;
               inventory = !inventory;
               inventoryUI.SetActive(inventory);

     }
     if(!Input.GetButtonDown(Buttons.TRIANGLE))
          isPressed = false;
...
}

When you press the button, the isPressed variable turns into true and the code is executed. However, the script now requires that the button be released in the previous frame. isPressed turns false only if the button is released. This ensures that inventory doesn’t switch every time Update() gets called.