Game Development Reference
In-Depth Information
1. To use the new script wizard, right-click inside the
Chapter2
folder of the
Project
tab and add a C# script named
InteractiveObj
.
2. To enable our interactive object to rotate about its own axis at a user spe-
cified rate, we need to add two parameters: a rotation axis and a rotation
speed, as shown in the following code:
public Vector3 rotAxis;
public float rotSpeed;
3. We will add a private reference to the
customGameObject
component for
this
GameObject
so that we don't have to look it up at runtime. This can be
done with the following line of code:
private customGameObject gameObjectInfo;
4. We will also add an
ObjectInteraction
member variable. This will be the
code that specifies what will happen to our
gameObject
when the player in-
teracts with it. There may be many interactions that an interactive object can
implement; we will start our example with
OnCloseEnough
and will complete
this in the
OnTriggerEnter
method, as shown in the following code:
public objectInteraction OnCloseEnough;
5. In the
Start()
method, we will search for the
CustomGameObject
com-
ponent attached to
gameObject
. If it is found, we will store the reference
in the
gameObjectInfo
private variable. Remember to always check that
gameObjectInfo
is not null so that debugging the code is a straightforward
process, as shown in the following code:
gameObjectInfo =
this.gameObject.GetComponent<customGameObject>();
if (gameObjectInfo)
gameObjectInfo.validate();
6. In the
Update()
method, we will apply a simple rotation to the object around
the specified
rotAxis
parameter. We will rotate the object with the speed
given in
rotSpeed
multiplied by
Time.deltaTime
so that the number of
rotations is a function of the elapsed time rather than the frame time, as
shown in the following code: