Game Development Reference
In-Depth Information
In the Project panel, create a new script named TriggerScript. Edit with the following code:
#pragma strict
function OnTriggerEnter() {
Debug.Log("OnTriggerEnter");
}
function OnTriggerStay() {
Debug.Log("OnTriggerStay");
}
function OnTriggerExit() {
Debug.Log("OnTriggerExit");
}
Save the script. In the Unity editor, attach the TriggerScript to the Trigger game object. Select the
Console tab in the Project panel. Play, and click the sphere to move it forward. In the Console
panel you will see a similar result to
OnCollision()
, where there is one
OnTriggerEnter()
call, many
OnTriggerStay()
calls as the sphere rolls through the volume of the Trigger game object's trigger
collider, and finally one
OnTriggerExit()
call.
While testing
OnCollision()
functions, you changed the property of a game object's component by
changing the Color property of the Renderer. You can also enable and disable entire components.
Edit the
OnTriggerEnter()
function to the following:
function OnTriggerEnter() {
var triggerRenderer : Renderer = GetComponent(Renderer);
triggerRenderer.enabled = false;
}
This code breaks down as follows:
(1) var triggerRenderer : Renderer = GetComponent(Renderer);
Declares a Renderer reference type variable named
triggerRenderer
, then assigns to it the reference
to the Trigger game object Renderer component.:
(2) triggerRenderer.enabled = false;
Disables the Renderer component by setting its boolean
enable
property to
false
.
Save and play. As expected, the Trigger game object disappears from view as the Sphere game
object's collider comes in contact with the Trigger game object's trigger collider.
Oftentimes in the course of a game you may want to change a boolean value to its opposite. Rather
than explicitly assigning it a value of
true
or
false
, you can use the ! logic operator instead.
Change the second line of code in the
OnTriggerEnter()
function to:
triggerRenderer.enabled = !triggerRenderer.enabled;
Here you are reassigning the opposite boolean value to the Renderer component's enabled state. If it
is currently
true
it will be changed to
false
, and if it is currently
false
it is changed to
true
.