Learning C# by Developing Games with Unity 3D Beginner's Guide
上QQ阅读APP看书,第一时间看更新

Testing conditions with an if statement

If, if, if. If I do this… if I do that… What happens if…

Certainly you've had to make decisions about all kinds of things in your life every day. We all do it all the time without actually giving the process of making a decision much thought, if any. As we make daily decisions, most of the time we just do the decision processing in our head. Unity doesn't have that human luxury, so we have to write it out so Unity can know the conditions that lead to certain choices. Having to write the logic is the strange part of writing code for beginners, simply because people usually make the vast majority of decision without writing anything down first. However, it is very simple to do.

An if statement is the most common way GameObjects make decisions. Data used to make these decisions is the information usually stored in some variables. For an if statement it's as easy as saying "If my condition is met, then execute my code block."

Testing if conditions are true or false

A sampling of conditions that can be true or false:

  • The user pressed a button
  • The temperature is cold
  • The character died
  • The bear made big potty in the woods

General questions like these are answered by humans, usually, with either a yes or no. For Unity, the answers will be either true or false. For example: "the bear made big potty in the woods" is either true, or false.