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);
}
}
}
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