Game Development Reference
In-Depth Information
Save and playtest, and you will see that the Trigger game object disappears just as before. Now
copy this code to
OnTriggerExit()
:
function OnTriggerExit() {
var triggerRenderer : Renderer = GetComponent(Renderer);
triggerRenderer.enabled = !triggerRenderer.enabled;
}
Save and playtest again. Push the sphere and now the Trigger game object disappears as the
Sphere game object enters the trigger collider volume, then reappears when the Sphere game object
exits the trigger collider volume.
Now for some code to do something with the game object that collided with the Trigger game object.
After
#pragma strict
, declare a public float variable named
triggerForce
and assign it a value of 10:
public var triggerForce : float = 10;
Now edit your
OnTriggerStay()
function to the following:
function OnTriggerStay(other : Collider) {
other.rigidbody.AddForce(Vector3.up * triggerForce);
}
This is a remix of what you've done with
OnCollision()
, where the
other
parameter refers to the
other game object involved in the collision with the trigger collider, in this case the Sphere game
object. An upward force is applied to the Sphere while it is within the trigger collider's volume.
Save and playtest. The Trigger game object still disappears and reappears as the Sphere enters and
exits its volume, but now it moves up from the force applied to it in
OnTriggerStay()
. The Sphere will
still have a forward motion from the initial push that you gave it, so after a few bounces it will pass
beyond the boundary of the trigger collider.
As you review the
OnTriggerStay()
function in the Scripting Reference, you notice that the force is
applied from within a conditional (Figure
6-9
).
Figure 6-9.
Unity Scripting Reference for the
OnTriggerStay()
function