Game Development Reference
In-Depth Information
In the Project panel Assets ➤ Scripts folder, create a new script named DestroyProjectile and open it
in MonoDevelop. Edit the code as follows:
#pragma strict
function OnTriggerEnter(other : Collider) {
Destroy(other.gameObject);
}
Attach the script to the DestroyProjectileTrigger game object and save the scene. Play and watch
the projectiles disappear as they enter the trigger volume. Behind the scenes, Unity instantiates the
game object and the physics engine handles the movement as before, but now Unity has no more
calculations to do with the game object until it enters the trigger volume.
Placing the trigger volume right next to the elevated track will minimize the life span of the projectile,
gaining more efficiency in game performance. Change the Transform position to (-4, 10.5, 47)
and play.
The projectiles are disappearing at the far edge of the track, but the tracer trail that is still over the
track blinks out instantly, which doesn't look as good as it did when flowing all the way across. This
is an example of the tradeoffs involved in optimization. Which is more important, the visual effect of
the tracer or the efficiency gained by having the trigger volume so close to the elevated track?
You decide.
Also, from a gameplay point of view, what happens if the player character were to run or jump into it?
Uh oh—not good. You know from the KillOnTrigger script how to check the identity of other ,
so you can implement a solution if you choose to keep the trigger volume within reach of the
player character:
#pragma strict
function OnTriggerEnter(other : Collider) {
if (other.gameObject.name == "Projectile")
{
Destroy(other.gameObject);;
}
}
You might wonder why the player would jump off the side in the first place. It might be accidental,
it might be they are exploring, or it might be just for the heck of it. As you develop your games, you
must consider what they can do in addition to what they are “supposed” to do and take appropriate
steps to eliminate bugs as you just did here.
Object Pooling
You will learn more advanced solutions as you continue to build your programming skills. Object
pooling takes optimizing the projectile prefabs a step further. Instantiating and destroying objects
also has a notable computational overhead. Instead of instantiating and destroying game objects
over and over, an array of the game object prefabs is created as a “pool” to be drawn from as
needed, then returned to when no longer in use.
 
Search WWH ::




Custom Search