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

335
Views
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 answers
Answer question

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 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!