Game Development Reference
In-Depth Information
With C#, it doesn't really matter what order your functions are in the script, but the convention is to
put event-driven and custom functions below the Start and Update functions.
5.
Save the script, and drag it onto the bench.
Comment out the 3 print lines in the VariablesTest script, and save the
script.
6.
7.
Center the bench on the Walkway Center object.
8.
Click Play.
The console will print “ouch” once on startup, once as it hits the long walkway, and once when it
goes onto the slightly raised walkway piece under the Gateway. It would be better if you could tell
what it collided with so you could customize the message. Fortunately, it turns out that you can.
Many functions can be used in different configurations.
9.
Search the Scripting Reference for MonoBehaviour.OnCollisionEnter.
The function can take an argument of type Collision (Figure 5-42 ).
Figure 5-42. OnCollisionEnter's argument type
10.
Click on the Collision type in the example (or search for collision) to see what
information it stores.
Among the variables, you will see gameObject. This means you can get the object, and therefore,
its name property.
11.
Return to the ColliderTests script.
Change the OnCollisionEnter code as follows:
12.
void OnCollisionEnter (Collision theVictim) {
print (theVictim.gameObject.name + " got hit");
}
The variable, theVictim , of type Collision, is used to get the name of the gameObject the bench hits.
13.
Save the script, and click Play.
This time, you can see that it is the collider-containing walkway objects that are triggering the print
statement (Figure 5-43 ). Ideally, you would like to be able to exclude certain objects from causing
any reactions. If there was only one object, you could check it by name, but there are three different
objects that it would be nice to exclude.
 
Search WWH ::




Custom Search