Game Development Reference
In-Depth Information
When the sphere falls under the force of gravity, it will collide with the cube. The physics engine
will call OnCollisionEnter() , where "OnCollisionEnter" will print to the console, and a call to
GetRandomColor() generates a random color, which is then assigned to the material property of the
sphere.
As the sphere rolls across the cube, the physics engine calls OnCollisionStay() in each frame the
sphere is in contact with the cube, and "OnCollisionStay" is printed to the Console many times.
Finally, the sphere rolls off of the cube and the colliders are no longer in contact. When this happens,
the physics engine calls OnCollisionExit()."OnCollisionExit" will print to the Console, and a new
random color is generated and assigned to the sphere.
The Other GameObject
You can also get information about the collision itself, including a reference to the other object the
scripted object is colliding with. In MonoDevelop, edit the OnCollisionEnter() as follows:
function OnCollisionEnter(other : Collision) {
Debug.Log("OnCollisionEnter");
color = GetRandomColor();
other. gameObject.renderer.material.color = color;
}
Save the script. Return to the editor, save the scene, then play. Now the cube rather than sphere
changes color on initial impact.
Changing the color is just an example that is easy to follow in the editor. Remember that game
objects are made up of components, and you can affect any component's properties through your
script. The autocomplete function of MonoDevelop help you out here. Type other.gameObject.
to see your options (Figure 6-4 ).
Figure 6-4. autocomplete selections for gameObject
Let's put these pieces together into a simple game prototype, but first take a moment to make sure
your project is organized with scripts in the Scripts folder, prefabs in the Prefabs folder, and scenes
in the Scenes folder. If you don't have any of these folders, select the Assets folder, then Create ➤
Folder and name it appropriately.
 
Search WWH ::




Custom Search