Game Development Reference
In-Depth Information
Billboards and Cached Transforms
The critical feature of Billboard functionality is that it rotates a sprite to face the camera.
Consequently, any Billboard class must access the Transform component of a GameObject on
every frame, to achieve a permanent state of object rotation using any of Transform's members or
functions, such as Transform.rotation , or Transform.Rotate , or Transform.RotateAround . These
members and functions can be accessed easily for any component on a game GameObject by
referencing its internal property, known as transform (lowercase t). For example, you may access an
object's Transform and translate it in world space with the following code in Listing 4-2.
Listing 4-2. Using the transform Property
void Update()
{
//Sets the object's world positon to 10, 10, 10
transform.position = new Vector3(10, 10, 10);
}
Now, although the code in Listing 4-2 works and achieves its purpose, it can still be improved in terms
of performance and efficiency, albeit marginally so. The main problem with the code is that, during
Update , a reference to transform is being made, which is a C# property and not a member variable . This
means that every call to transform indirectly invokes a function ( Property ), which returns a reference
to the Transform component. transform does not, however, access an object's Transform directly, as
a member variable would. Remember, C# properties were covered in depth in the previous chapter.
Because transform is a property, there is a small optimization we can perform, known as Cached
Transforms . Consider the refined Billboard class in Listing 4-3, which uses Cached Transforms.
Listing 4-3. The Billboard Class Prepared for Action with Cached Transforms
01 using UnityEngine;
02 using System.Collections;
03
04 public class Billboard : MonoBehaviour
05 {
06 private Transform ThisTransform = null;
07
08 // Use this for initialization
09 void Start ()
10 {
11 //Cache transform
12 ThisTransform = transform;
13 }
14 }
Listing 4-3 shows how, in just two lines of code, we can create a Cached Transform object.
In essence, using the Start event (at line 09), we store a direct and local reference to an object's
Transform component with the private Transform member ThisTransform . ThisTransform is a
member variable and not a property, and gives us direct and immediate access to the transform
component. Consequently, by using ThisTransform instead of transform on Update functions, we
can reduce additional and unnecessary functional calls on every frame. This may initially seem a
 
Search WWH ::




Custom Search