Error with If statement

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.

1 Like

A comparison uses two egual signs, you are only using one on the second if statement.

1 Like

Thanks Timelog that works but you are right I was looking for a error and it doesnt happen.

Nothing to do with whether or not it is in an if statement - It just isn’t a compilation error. A single equal sign is a valid assignment operation.

Also, when using booleans in an if, it is redundant to compare with ‘== true’

 bool myBool=true;
if (myBool==true) //this is equivalent to the below statement
if(myBool) //this is equivalent to the above statement

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.

1 Like

I wonder about this too. I know that Pascal compilers give an “Expected type Boolean expression” when you try to do this

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.

3 Likes

@Zaladur thanks for you explanation! Makes total sense

1 Like

Thanks for the explanation, it makes a lot of sense indeed :slight_smile: