I am working on a game that when a mana level get to 0 you have to wait out a recharge or watch a ad. I have everything else working but I get a wired loop in my statement.
if (PlayerPrefs.GetInt (“Mana_current”) == 0) {
Debug.Log("Before If " + Random_event.Run);
if(Random_event.Run = true){
Random_event.Run = false;
Debug.Log("After If " + Random_event.Run);
}
Now it should only run Random_event.Run = false; once but I get this in my debug log.
“if(Random_event.Run = true)” should be “if(Random_event.Run == true)”
I has something like this myself some time ago as well, and it seems like, if there is an error in an if statement, it just gets ignored instead of an error being thrown. No idea why though.
What I am wondering though, is WHY an assignment operation within the if statement is not a compilation error. What is the use of an assignment operation within a comparison operation? Personally I would expect C# to throw an error at that point.
Essentially, an assignment operator has a return value - the value of the lefthand side variable after the completion of the statement. So the line
bool a = false;
will return a value of false;
bool a=false;
bool b;
a=(b=true);
Debug.Log(a);
The above should print True, because a was assigned the return of (b=true), which was ‘true’.
Therefore
bool a=false;
if (a=true) Debug.Log ("True");
else Debug.Log ("False");
This code should print ‘True’, because the return of ‘a=true’ was true.
If you try any NON-bool assignment operation inside an if statement, you will get a compile error.
int a=0;
if(a=1) Debug.Log ("A is 1");
This throws a compilation error because the return value of ‘a=1’ is the int 1. The error should be along the lines of "Cannot implicitly convert type ‘int’ to ‘bool’. The error is because the return value of the assignment is an int, and you are attempting to use it as a bool.
Good editor programs may point out boolean assignment operators inside of if statements, and maybe throw a warning, but they do not throw an error because it is all completely valid.