Blue_Galaxy Gamer
Blue_Galaxy Gamer

Reputation: 11

How to check if the gameObject is active or not

I am making a backpack and I am trying to make it like Minecraft how you just press "E" and it will open and if is already open then they close it. Bty I am using Unity in C#.

if (Input.GetKeyDown(backpackKey) && backpack.activeInHierarchy == false)
{
   backpack.SetActive(true);
}
if (Input.GetKeyDown(backpackKey) && backpack.activeInHierarchy == true)
{
    backpack.SetActive(false);
}

Upvotes: 0

Views: 18593

Answers (2)

derHugo
derHugo

Reputation: 90620

Both your if conditions will match:

  1. your object is inactive
  2. You set it active
  3. Now also the second condition matches
  4. You set it inactive again

Either use else if to make both blocks run exclusive or .. actually you could simply do

if (Input.GetKeyDown(backpackKey))
{
    // I would prefer using "activeSelf"
    // If any parent is inactive your check might always return false even though the object
    // itself is already set to active. Don't know if it has an impact on performance
    // I just find it more convenient here since this is the value changed by "SetActive"
    backpack.SetActive(!backpack.activeSelf);
}

Upvotes: 5

lucasreta
lucasreta

Reputation: 938

You are missing an else statement:

if (Input.GetKeyDown(backpackKey))
{
  if(backpack.activeInHierarchy == false)
  {
    backpack.SetActive(true);
  } else {
    backpack.SetActive(false);
  }
}

In your code, whenever you try to open it then you end up falling into the second condition, now true, and closing it immediately.

Upvotes: 0

Related Questions