Game Development Reference
In-Depth Information
Figure 5-32. Increasing the Ear Length value by 2
You did a bit of math in the previous bit of code you added. In scripting, you can make use of the
usual operands (+, -, / and *). For modulus (the remainder after division), you can use %. The order
of evaluation is the same as regular math: * and / are evaluated first, followed by + and -. You will
often see shortened versions of these operations in code. Let's try one.
Change the earLength line to the following:
1.
earLength += 2.0f; // add to the value and re-assign it
2.
Save the script, and click Play.
The results are the same.
While numbers, strings, and Booleans are easy to initialize or set up in the Inspector, Unity-specific
types take a bit more work. Dragging a single gameObject into a parameter's value field is easy
enough, but if you had multiple objects with the same script component that all required the same
gameObject, it would become quite tedious. For this scenario, you can let Unity “find” the object by
name. This process is relatively slow, so it should be used only in the Start function or after one-off-
type events, where speed is not an issue. Let's assign the same gameObject as the Favorite Food to
all of the gameObjects with the test script.
Select the earLength and print lines, and apply Toggle Line Comments from
the right-click menu so they will be ignored.
1.
2.
Add the following lines below them:
favoriteFood = GameObject.Find("Carrots");
This time, GameObject is capitalized because you are using the GameObject class's Find() function.
Also, because you are using a string to identify the object of the search, the name must be exactly as
it is in the Hierarchy view. Be especially careful with spaces and capitalization.
3.
Now add the following line to print the results:
print("The " + gameObject.name + "'s favorite food is " + favoriteFood.name + ".");
In this line, you are referring to specific gameObjects, so gameObject is not capitalized.
4.
Save the script, and click Play.
 
Search WWH ::




Custom Search