Transforming, following, and accessing objects (and their children)

Introduction

In this post we will be looking at how effectively use Transforms in you code to be able to implement some interesting (and much needed) effects and features including: translations, rotations, and animations.

Simple Transformations in Unity

Whenever an object is created in the Scene view, it includes a transform attributes that deals with the objects position, rotation and scale. So Unity provides a few useful functions that make it possible to modify these parameters so that you can translate, rotate, or scale an object from a script. Let’s look at the following snippet to see how it can be done:


void Start ()

{

GameObject g = GameObject.Find ("Cube");

g.transform.Translate(new Vector3(1,0,0));

g.transform.Rotate (new Vector3 (0, 45, 0));

g.transform.localScale = new Vector3(2, 2, 2);

}

In the previous code:

  • We create a reference to the object called Cube.
  • We then translate (move linearly) this object to a new position.
  • We also rotate this object using the function Rotate. The rotation uses what are called Euler Angles; so we use a vector notation to perform the rotation; the x coordinate indicates the amount of rotation (in degrees) around the x axis, the y coordinate indicates the amount of rotation (in degrees) around the y axis, and the z coordinate indicates the amount of rotation (in degrees) around the z axis. In our case; so in our case, we rotate the object 45 degrees around its y axis.
  • In the last line of code, we rescale the object, using a vector notation for which the x, y and z coordinates indicate the scale factor on the x, y and z axis, respectively.

Using Lerp for Animations and smooth transtions

Now there are times when you’d like to perform a smooth transformation that is performed overtime; in this particular case, you can use what is a Lerp. In Unity, a lerp will be used to perform an interpolation between two values (e.g., vectors, colors, angles, etc.). Interpolating means that given two values (starting and ending), we can guess values in-between. Let’s take the example of a journey between two cities A and B; if we know our speed (that is constant), our starting time and the time of arrival (i.e., the duration of the journey), we can predict at what time we will have completed half of the journey: this is called interpolation. So let’s look at how this could translate for a Translation in Unity.


GameObject g;

float startTime, currentTime, duration;

void Start ()

{

g = GameObject.Find ("Cube");

startTime = Time.time;

duration = 5;

}

void Update ()

{

currentTime = Time.time;

float percentage = (currentTime - startTime) / (duration);

g.transform.position = Vector3.Lerp (new Vector3 (1, 0, 0), new Vector3 (10, 0, 0), percentage);

}

In the previous code:

  • We declare the variable as we have done before.
  • We also declare three variables called: startTime, currentTime and duration.
  • The variables startTime and duration are initialized in the Start
  • At this stage we have set the variables to be used for the Lerp; however, when we use a Lerp, we need to specify the initial position, the end position, as well las the where we are in relation to the full duration of the journey; in other words, we need to be able to determine the proportion of the journey that we have completed.
  • This can be done by establishing a ratio that ranges from 0 to 1 (not completed to fully completed) and that can be calculated as a ratio between the time elapsed since we have started the journey (currentTimestartTime) and the duration of the journey (e.g., variable duration).
  • So the last line completes this tasks by using the vector3.Lerp function and specifying the start position (1,0,0), the end position (10,0,0) as well as the percentage f the journey that is completed at this point (percentage).

 

This technique is very useful and you can of course apply the same principle to interpolate between floats (Mathf.Lerp), rotational values saved as Quaternions (Quaternion.Lerp) or colors (Color.Lerp).

Looking for objects in Unity

In addition to moving objects, the Transform class also offers some other interesting features such as searching for an object among the children of a parent object. This can be done using the methods Transform.Find and refers to the transform attribute of, as illustrated in the next code snippet. Let’s imagine that we have created an object called “Cube1” and that we have also created two other objects called Cube2 and Cube3 that are children of this the object Cube (i.e., we have created them and dragged and dropped them on the object Cube) .

 

So we could create a script that is linked to the parent object (i.e., Cube1) that finds some of the children of the object Cube1.


void Start ()

{

Transform t2 = transform.Find ("Cube");

Transform t3 = transform.GetChild (0);

print (t2.gameObject.name+"was found as a child of"+gameObject.name);

print (t3.gameObject.name+"is the first child of"+ gameObject.name);

}

In the previous code:

  • We declare two Transform objects t2 and t3; this is because the functions Find and transform.GetChild both return a Transform object.
  • t2 refers to the transform attribute of a child of the current object with the name Cube2.
  • t3 refers to the transform attribute of the first child of the current object; note that the child at the index 0 is the first child;
  • We then print information about these two objects. The name of the game object corresponding to Transform object t2 is retrieved using the syntax: gameObject (we use a lower case here as we refer to the object – not the class – that is linked to the transform)
  • We also saw that an object can, in turn, have children.

The method GetChild is useful if, for example, there are several items with the same name in the scene, but you just want to access an item that is related to a specific parent; for example, if all NPCs in your scene have a gun with a label called gun, and you want to deactivate the gun of a specific NPC, then the method GetChild might be handy. If you were to use GameObject.FindWithTag(“gun”), this method would return several guns (or all the guns with a tag called gun) in the scene; however, if, instead, you selected a particular NPC GameObject, its gun (provided that it is a child of the NPC) can be found using the syntax npc.getChild(“gun”) provided that the name of the gun GameObject is gun.

Rotating towards (or looking at) an object

Last but not least, we will look at the method called LookAt; this method is useful when you’d like a character or an object to face a particular direction; this can be used for NPCs to make sure that they always look at the player. This could also be used so that a camera is always looking at a particular item in your scene. Let’s look at how this can be done using the following snippet.


void Update ()

{

transform.LookAt (GameObject.Find ("target").transform);

}

In the previous code:

  • We use the Update function so that the information is updated frequently.
  • We then use the method LookAt to make sure that the current object is oriented towards an object called target.

Because the method LookAt works with Transforms, we need to obtain the transform from the object that we want to look at.

Save

Save

Save

Save

Related Articles: