Learn how to create an avatar with Unity and enjoy it in virtual reality (VR) in this tutorial by Jonathan Linowes, a VR/AR evangelist, Unity developer, entrepreneur, and teacher.
Gaming is a common application of virtual reality, so you might as well start from there! With the help of this tutorial, you will give a character, Ethan, a life of his own. Well, sort of (or not), because he's going to become a zombie!
Bring Ethan to Life
Unity comes with a third-person character named Ethan. He's one of the Standard Assets in the Characters package. You can import him into your project.
To import, perform the following steps:
Now, try this out:
Ethan, the Walker
Now that you have brought Ethan to life, you can make him run around the scene if you have a hand controller with a thumbstick or touchpad, but that is not guaranteed on some VR devices. In fact, if you're viewing the scene with Google Cardboard, it's pretty unlikely that you'll have a handheld controller (notwithstanding the Bluetooth game controllers). However, you can consider another way to make him move around, using the direction of your gaze while wearing your VR headset.
Before you attempt this, you need to first transform Ethan into a zombie and have him walk around aimlessly without any user control. You can do this by giving him some AI and writing a script that sends him to random target locations. AI controllers and NavMesh are somewhat advanced topics in Unity, but you’ll get a glimpse into it just for fun. Besides, it's not as scary as zombies.
Artificially Intelligent Ethan
First, you must replace the
ThirdPersonController prefab that you used initially with Unity's AI character,
AIThirdPersonController, using the following steps. Unity uses the word artificial intelligence loosely to mean script-driven. You can do this by performing the following steps:
Characterspackage imported from
Projectpanel, open the
Standard Assets/Characters/ThirdPersonCharacter/Prefabsfolder and drag
AIThirdPersonControllerinto the scene. Name it
Hierarchypanel (or in
Scene), select the previous
ThirdPersonController, (the old Ethan). Then, in the
Transformpane, choose the gear icon on the upper right of the
Transformpane and select
Ethanobject (from the
Scene). Then, in the
Transformpane, choose the gear icon and select
Paste Component Values.
Ethanobject by selecting it from the
Hierarchypanel, right-clicking to open options and clicking on
Note that this controller has a
NavMesh Agent component and an
AICharacterControl script. The NavMesh Agent has parameters for how Ethan will move around the scene. The
AICharacterControl script takes a target object where Ethan will walk to. You can populate that as follows:
Hierarchypanel and rename it
Transformvalues to position (
0) (using the gear icon in upper-right of the Transform pane).
Targetproperty in the
AI Character Controlpane, as shown here:
At this point, you have an AI character in the scene (
Ethan). You can also create an empty game object that can be used as a navigation target (
WalkTarget) initially in the center of your scene and tell the AI Character Controller to use this target object. When you run the game, wherever
WalkTarget is, Ethan will go there but not yet.
Ethan cannot just go walking around without being told where he's allowed to roam! You need to define a NavMesh, a simplified geometrical plane that enables a character to plot its path around obstacles.
In your scene, Ethan is an agent. Where he's allowed to walk is the navmesh. Note that he has a NavMesh Agent component and an
AICharacterControl script. The NavMesh Agent has parameters for how Ethan will move around the scene.
NavMesh by first identifying the objects in the scene that affect navigation by marking them
Navigation Static and then baking the NavMesh, as follows:
Navigationpanel. If it's not already a tab in your editor, open the
Navigationwindow from the main menu by navigating to
Hierarchy, then, in the
Navigationwindow's Object pane, check the
Navigation Staticcheckbox. (Alternatively, you can use the object's Inspector window Static dropdown list.)
Baketab and click on the
Bakebutton at the bottom of the panel:
Scene view should now show a blue overlay, where the NavMesh is defined, as shown in the following screenshot:
It’s time to test this out. Ensure that the
Maximize on Play is deselected. Click on the Play mode button (the triangle at the top of the editor). In the
Hierarchy panel, select the
WalkTarget object and ensure that the Translate gizmo is active in the
Scene panel (press the W key on keyboard). Now, drag the red (
x) and/or the blue (
z) arrow handles on the
WalkTarget object to move it around the floor plane. As you do, Ethan should follow! Click on Play again to stop
You will now learn to write a script that moves the
WalkTarget object to random places.
Writing scripts is an important part of developing with Unity. If you've done anything more that tinker with Unity, you've probably already written at least some scripts. You are going to use the C# programming language for this.
For this first script, you can attach the script to the
WalkTarget object, as follows:
WalkTargetobject in the
Hierarchypanel or the
Inspectorpanel, click on the
New Script(you may need to scroll down to find it).
C Sharplanguage is selected.
Create and Add.
WalkTargetobject. Double-click on the
RandomPositionscript in the slot to the right of
Inspectorpane to open it in your code editor.
Since you want to move the
WalkTarget object to a random location so that Ethan will head in that direction, wait a few seconds, and move the
WalkTarget object again. That way, he'll appear to be wandering around aimlessly. You can achieve this with a script. Here is the finished version first, and you can go through it line by line. The
RandomPosition.cs script looks like this:
This script defines a
MonoBehaviour sub-class named
RandomPosition. The first thing to do when defining the class is to declare any variables that you'll use. A variable is a placeholder for a value. The value can be initialized here or assigned elsewhere, just as long as it has a value before the script uses it.
The meat of the script is further down, the function named
GroundPlane plane of 10 units square, with the origin in the middle, so, any (x, z) location on the plane will be within a range from
5 along each axis. The line
float x = Random.Range (-5.0f, 5.0f) picks a random value within the given range and assigns it to a new
float x variable. You can do the same thing to get a random
Debug.Log ("X,Z: " + x.ToString("F2") + ", " + z.ToString("F2")) line prints the
z values in the
Console panel when the game is running. It'll output something like
X, Z: 2.33, -4.02 because
ToString("F2") says round up to two decimal places. Note that you're using plus signs to combine the parts of the output string together.
You can actually move the target to the given location with the line
transform.position = new Vector3 (x, 0.0f, z);. You can set the transform position of the object to which this script is attached to. In Unity, values that have an X, Y, and Z are represented by the
Vector3 objects. So, you need to create a new one with the x and z values that you generated. You can use
y=0 so that it sits on
MonoBehaviour class has a built-in variable called
this, which refers to the object that the script is attached to. This means when the script is a component of an object and appears in its
Inspector panel, the script can refer to its object as
this. In fact,
this is so obvious, if you want to call functions on the
this object, you don't even need to say it. You could have said
this.transform.position = ..., but the
this object is implied and is normally omitted. On the other hand, if you had a variable for some other object (for example,
GameObject that;), then you'd need to say that when you set its position, like
that.transform.position = ....
The last mysterious bit is how you handle time delays in Unity, using co-routines. This is a somewhat advanced coding technique, but very handy. In your case, the transform position should get changed once every five seconds. It's solved in several parts:
Start()function, there's the line
StartCoroutine (RePositionWithDelay());. A co-routine is a piece of code that runs separately from the function from which it was called. So, this line kicks off the
RePositionWithDelay()function in a co-routine.
while (true)loop, which as you might guess, runs forever (as long as the game is running).
SetRandomPosition()function, which actually repositions the object.
yield return new WaitForSeconds (5);statement, which basically says to Unity, hey, go do what you want for five seconds and then come back here so that I can go through my loop again.
RePositionWithDelayco-routine must be declared as the
IEnumeratortype (because the documentation says so).
This co-routine/yield mechanism, although an advanced programming topic, is a common pattern in time-sliced programs such as Unity. You can save the script to a file named
You are now good to go. In the Unity editor, click on Play. Ethan is running from one place to another like a madman!
OK, that's pretty random. Adjust the NavMesh steering parameters to slow him down to a nice zombie-like pace. For that, perform the following steps:
Nav Mesh Agent|
Steeringand set the following:
Play again. He has slowed down. That's better.
One more finishing touch: turn him into a zombie. You can select a texture image named
EthanZombie.png that will help and perform the following steps:
Assetstab on the main menu, select
Import New Asset.... Navigate to the files folder where you have saved the file.
Import. For tidiness, ensure that it resides in the
Assets/Texturesfolder. (Alternatively, you can just drag and drop the file from Windows Explorer into the
Projectpanel Assets/Textures folder.)
Hierarchypanel, unfold the
Ethanobject (click on the triangle) and select
Inspectorpanel, unfold the
EthanGrayshader by clicking on the triangle icon to the left of
EthanZombietexture from the
Albedotexture map. It's a small square just to the left of the
EthanGlassesand uncheck it to disable glasses in the
Inspectorpanel. After all, zombies don't need glasses!
Here is a sample portrait featured below. What'd you say? That's not a scary enough zombie?? Well, maybe he's just recently turned. Go ahead and make a better one yourself. Use Blender, Gimp, or Photoshop and paint your own (or even import a whole different zombie humanoid model to replace
Now, build the project and try it in VR. You will have a view from a third-person perspective. You can look around and watch what's going on. It's kind of fun, and it's pretty interesting.
If you enjoyed reading this article, you can refer to Unity Virtual Reality Projects - Second Edition for creating more than 10 engaging projects with Unity 2018. This book will help you explore the latest features of Unity 2018 to create rich, interactive virtual reality experiences for Oculus Rift, HTC Vive, Daydream and Gear VR.
Please login to post your valuable comments.
Get the latest vLemonn news first