Chapter 5. Making Decisions in Code

One of the primary duties of a computer is controlling what happens next when certain conditions are met. That's what computers do whether the code is controlling an application or a game. We write scripts to make GameObjects behave a certain way one moment, then the behavior should change when the conditions change. A script has to detect when the conditions change, then make the appropriate code execute based on the new conditions. This chapter looks at some examples of the ways that conditions can change, and the code to detect these changes. This in turn determines which code in the script is executed next.

In this chapter we will discuss:

  • If statement decisions
  • Checking for many conditions
  • If-else statement decisions
  • User's input condition changes
  • Looping though data in an Array, List, or Dictionary

Let's begin...

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.251.128