Game Development Reference
In-Depth Information
Caching Component Lookups
This scripting technique is particularly effective for scripts that are used frequently, but the tradeoff
is that it takes a little more code. The GetComponent() function is an example of a lookup . Finding
the component in the game object takes time and affects performance. The idea here is to look up a
reference once, then cache or store the reference in a private variable to be available for use in the
script later. In other words, avoid using GetComponent() in the Update() or FixedUpdate() functions
where possible. You have used this technique in your GoRagdoll script:
#pragma strict
private var childRigidBodies : Rigidbody[];
private var childColliders : Collider[];
public var invincible : boolean = false;
function Start ()
{
childRigidBodies = gameObject.GetComponentsInChildren.<Rigidbody>();
childColliders = gameObject.GetComponentsInChildren.<Collider>();
}
...
The ragdoll rigidbodies and colliders were found with the GetComponentsInChildren() function
lookup, then assigned to their respective arrays in the Start() function.
More Scripting Optimization Alternatives
Anywhere you can reduce or avoid frame-by-frame computations improves performance. Some of
these are more advanced methods not covered in detail here, but you can explore them in more
depth when pertinent to a particular project.
Use Triggers
In the LaunchProjectile script, you reduced the number of projectile game objects that Unity
has to track on by using the Destroy() function to remove each projectile 2 seconds after it was
instantiated:
Destroy(projectileInstance, 2);
While this is definitely an improvement from letting the projectile clones pile up, Unity still has to
track each object and check its lifespan until it reaches 2 seconds. One alternative solution to the
Destroy() function would be to use a trigger instead. First, comment out this line of code.
In your Obstacle Course scene, create a Cube game object and name it DestroyProjectileTrigger.
Set its Transform position to (-12, 10.5, 47) and its scale to (1, 3, 10). Remove the Mesh Filter
and Mesh Renderer components so you have a simple Box Collider. Check Is Trigger in the Box
Collider component.
 
Search WWH ::




Custom Search