Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

427
Views
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);
}
over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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);
}
over 4 years ago · Santiago Trujillo Report

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!