Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

428
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda