There is a simple code that is connected to a button.

public void Inc() { if (x < 5) { x++; Debug.Log(x); } Debug.Log("Done"); } 

In theory, I expect that after five clicks on the button, the message Done will appear. But Done, appears after each increase in X by 1 unit. enter image description here

  • Sorry, but the if statement is irrelevant to the loop. This is a branch. - Alexander Danilovsky
  • To be perfectly accurate, this condition) But the essence of the issue does not change. Why is Done displayed before the condition is met? - Amateur
  • Why before? The first line in the logs: 1. The second line - Done. Etc. Everything works correctly. Or am I missing something? - Alexander Danilovsky
  • In words, the condition looks like this: If X is less than 5, then increment X by 1, and then output a message with the value X to the console. That is, Done should appear if X is greater than 5. - Amateur
  • The conclusion I expect: 1 2 3 4 5 Done - Amateur

1 answer 1

 public void Inc() { if (x < 5) { x++; Debug.Log(x); } else Debug.Log("Done"); } 

The Inc () method of your code always displays the message "Done" in the log, because if the condition (x <5) is true, then there is no way out. Therefore, it is necessary either after if to use else, or after Debug.Log (x) to use return.

Only now drew attention to the "five clicks." In this case, after checking x <5, one should also check for equality 5. Then, in one execution of Inc (), the increment and output of the message that the task is completed will be possible.

 if (x < 5) { x++; Debug.Log(x); } if (x == 5) Debug.Log("Done");