- Home /
Variable doesn't change in Unity methods
I've got a bool variable declared in the main script. When I try to change it in any Unity method (OnTriggerEnter, OnDestroy, ...), it only changes inside of it, not globally.
public class Main : MonoBehaviour {
private bool gameOver = false; // the bool variable
void OnTriggerEnter(Collider other)
{
if(other.tag == "Finish")
{
finish = true;
return;
}
gameOver = true;
Instantiate(explosionEffect, ship.transform.position, Quaternion.identity);
Destroy(ship);
}
void OnGUI()
{
if(gameOver)
{
// do sthing
}
}
How come?
I can't say I've had that problem. Can you post enough code for someone else to reproduce the problem? Something else is probably causing the problem. If I had to guess, either your collision handler isn't being called or you're referencing the wrong object.
@rutter I've changed my post. This is all the interaction with that variable. The OnTriggerEnter is called, I've checked. Oh... is OnGUI() the problem maybe? :O
Okay, now this is weird. Now my variable changes inside Unity methods, and not inside other ones... I must be making a mistake somewhere.
I am not sure, but can it be that the Return Statement kick you Out of the function before the Variable change?// Are you destroying the Objekt your script is on? Your Code dont seem to cause any problem. debug a bit.
Your answer
![](https://koobas.hobune.stream/wayback/20220613150210im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to assign a private transform of my player in script? 1 Answer
Says that variable has not been assigned(but I already did). 1 Answer
Is there a way to make a variable correspond to multiple different scripts? 1 Answer
How to call variable from java script to c# Script? :( 2 Answers
Static Variable Problem 1 Answer