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

338
Visualizações
Unity C# variable not working inside OnCollisionEnter

I'm working on a game that is about basically rolling a ball and when you hit gameover object it's gameover, when you hit goal object it's goal (and maybe you'll be navigated to next stage or whatever), and here I want algorithm it will be ignored when you hit gameover object after you hit goal object, so once you hit to the goal object you'll win the stage.

Here the C# code, I set variable goaled and tried to change the variable to "true" when you hit the goal object, and when only if goaled == false, when not yet you goaled, you'll be lose. But the code doesn't work, as a expected result it shouldn't log "gameover" after I goaled, but actually it will.

So, how can I modify the code to work as expected? Thanks.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class tmp03 : MonoBehaviour
{

    bool goaled = false;

    void OnCollisionEnter(Collision otherObj)
    {

        // bool goaled = false;

        if (gameObject.name == "goal" && otherObj.gameObject.name == "ball")
        {
            Debug.Log("goal");
            Debug.Log(goaled);
            goaled = true;
            Debug.Log(goaled);
        }
        if (gameObject.name == "gameover" && otherObj.gameObject.name == "ball" && goaled == false)
        {
            Debug.Log("gameover");
            Debug.Log(goaled);
        }

    }

}
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

As far as I understand from your code, specifically from the lines gameObject.name == "goal" && otherObj.gameObject.name == "ball" & gameObject.name == "gameover" && otherObj.gameObject.name == "ball" && goaled == false, it seems to me as if you are adding this script to both the goal and gameover gameobjects.

These are TWO DIFFERENT script instances. They will not share the goaled property between them. If you want to track only ONE goaled property, you should add the script only once (in this case, to the player) and inverse the if conditions. Have the ball be the primary gameObject, and the gameover object and goal as the otherObj

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