Professional Documents
Culture Documents
##############
AARON HIBBERD
U N I T Y 101
SECOND EDITION
###########
###########
Setup ..............................................................................................................3
First we’ll start a new project with a simple cube to use as the player, and learn how to
look around the scene.
START A NEW PROJECT
Create a new Project, 3D (URP) Core, this will open an empty project.
In the Inspector window, click on “Remove Readme Assets” to get rid of unnecessary les.
Using the SampleScene, File > Save As, to save the scene as level01 in the Scenes folder.
In the Project folder, you can right click and delete the SampleScene.
fi
SCENE SETUP
In the Hierarchy window, click the Plus dropdown, Create, 3D Object, Cube.
With the player selected in the Hierarchy, go over to the Inspector window, and set the
player position to 0,0.5,0.
While the player is still selected, move the mouse over the Scene window, and press F to
nd the player.
With oor selected, in the Inspector window, in the Transform component, click the 3 little
dots at the top right, and click reset, to quickly set the oor position to 0,0,0.
Right click the Materials folder and create a new material called “player”, and a new material
called “ oor”.
With a material selected, you can change its color in the Inspector window.
Make the player material a color like green, and the oor material a di erent color like blue.
You can drag the materials right onto the gameObjects in the Scene window, and this will
add it to their components.
fi
fl
fl
fl
fl
fl
ff
LOOK AROUND
In the scene view, you can scroll your mouse wheel to zoom in and out, or you can hold ALT
and the right mouse button, and move to zoom.
While still holding the right mouse button, you can use the WSAD keys to move.
You can hold ALT and the left mouse button, and move to rotate around.
Find viewing position that you like for looking at the cube.
Now the camera should move to match that nice view angle and position.
If the gizmos are too big and annoying, you can shrink them in the gizmos drop down, or
you can toggle them o .
Next we’ll write a simple script to control the player. It will translate and rotate the player
when we press the arrow keys.
UPDATE LOOP
Make sure the class name at the top is "player", not “NewBehaviorScript".
There is a Start() when we play the game, rst this happens once.
The speed of Update will uctuate with the frame rate of the game.
Go back to Unity and wait for the loading at the bottom right to nish while it compiles the
script.
Select the player gameObject in the hierarchy, it's components are listed in the Inspector
window.
Drag the player script onto the inspector window to add it to the player gameObject. Or
press “Add Component” and type the word player to nd the script.
Press play and see in the Console window how our code in the update loop happens every
frame.
print(Time.time);
Press Play, you can see the time since the game started running.
print(Time.deltaTime);
Press Play, you can see the time since the previous frame. You can see how inconsistent it is,
it's just however fast your device is running.
TRANSL ATE
All the things on the inspector, that are attached to the player, are called components.
Look at the Transform component, you can drag on Position X, Y, or Z, and it's going to
change the player position in the scene.
We want to manipulate these from the code, open the player script.
transform.Translate(0.01f,0f,0f);
We are going to the transform component on this gameObject, and using Translate to add to
the positions.
So the rst one is X, I'm going to add 0.01f to the X position every frame.
You can change the Y and Z too, use whatever numbers you want.
The player moves 0.01f in X every frame, but the frames don't happen at a perfectly
consistent speed. So on devices with di erent frame rates, it is not moving at the same
speed.
transform.Translate(1f*Time.deltaTime,0f,0f);
When we multiply our value by the time since the last update, we are making it consistently
move the same speed every frame. This will move the position by 1 every 1 second.
transform.Translate(2f*Time.deltaTime,0f,0f);
This will move the position by 2 every second. It will move consistently at the same speed
even though the frame rate isn't consistent. So on di erent devices it should still behave the
same.
This value is public, so we will be able to see it, in the Inspector window. We are calling it
speed, we can call it any name we want. By default it is set to 2f, but we can change it in the
Inspector window.
transform.Translate(speed * Time.deltaTime,0f,0f);
Now when we play the game, we can see our speed value in the inspector, and we can adjust
it to move faster, slower, or in reverse.
Do this to determine what speed you like moving, and what would be a good number to use
by default.When you press stop, most changes made during play mode will be lost.
I like 4, so I'm going to set speed to 4 in the inspector, this will override the default of 2.
If you don't have them, click the gear in the top right, and click “reset".
If you open Horizontal, you will see it has the name “Horizontal".
You can see they have positive and negative buttons, they are a ected by the Arrow or
WASD keys.
print("horizontal "+Input.GetAxis("Horizontal"));
We are going into the Input and getting the value for the axis called “Horizontal”, which is a
number that represents how much the axis is being pressed. And the same for “Vertical”.
If it was a joystick pushed all the way to the right, the Horizontal value would be 1, if it's
pushed all the way to the left, it would be -1, and if it's in the middle, not being pressed, it
would be 0.
Play the game and see in the output window how the numbers change, based on how you
are pressing the arrow keys.
ff
MOVE THE CUBE
So now we'll use those values to move the cube in the direction we press.
Let’s remove the print, and put Horizontal and Vertical into the X and Z of Translate.
You can use two forward slashes to turn a line into a comment.
This is good for disabling code, and for writing notes to document what your code does.
Now when you play the game, you can move the cube with the arrow keys.
Rotate works much the same as Translate, lets make it rotate with the same controls.
Inside the Update(), copy paste the Translate line, and comment out the old line.
Now when we play, we can use the arrow keys to rotate instead of translate.
You can change the Turn Speed value in the inspector, if you don't like 100.
fl
INVERSE TRANSFORM DIRECTION
I want to use the up/down arrow keys to translate forward/back, and use the left/right
arrow keys to rotate left/right.
We want to use inputY to move forward/back along the axis that is forward in whatever
direction the player is currently facing.
While the player is selected in the Hierarchy, we can see blue, red, and green arrows on the
player in the Scene window. Red is the x-axis, Green is the y-axis, and blue is the Z-axis.
At the top of the Editor, there is a button to toggle between 'Global' and 'Local'.
While we are set to 'Global', the axis show world space, kind of like North, South, East,
West. Rotating the player will not a ect the arrows, because they are directions in the
world.
While we are set to 'Local', the axis show local space of the currently selected GameObject's
Transform. Now when we rotate the player's Transform properties, the arrows will rotate
because the axis are in local space, like Front, Back, Left, Right of the GameObject's
transform.
Go back to the script, transform.forward is a Vector3 representing the Z-axis (blue arrow) of
this transform in world space. InverseTransformDirection converts a Vector3 from world
space, to local space. Replace the uncommented translate line with:
Now when we play, we can turn and move forward/back based on the direction the player is
currently facing, which works for very basic movement controls.
Next we’ll create a script to control the camera. It will look at the player, and smoothly
follow behind the player.
LOOK AT POSITION
Right-click the scripts folder, Create C# Script, and before pressing enter, name it
“playerCam”.
Wait a moment for Unity to nish compiling and then open the playerCam script.
Make sure the top of the script says "public class playerCam", not "NewBehaviorScript"
transform.LookAt(targetPos.position);
With the Main Camera selected, drag the player gameObject from the Hierarchy, onto the
'Target Pos' value of our Player Cam script, in the Inspector window.
Now we have the Transform of the player linked to the targetPos value of the playerCam
script, so in Update() the Camera will look at the player’s position.
Now when we play, the camera will always update to look at the player's transform position.
transform.LookAt(targetPos.position + targetOffset);
Now when we play, we can adjust the Target O set so the camera target isn't perfectly
centred.
I like Target O set (0,1,0) so it's looking slightly above the player.
Stop playing and set it to (0,1,0) or however you like it, to keep the values.
ff
ff
ff
FOLLOW POSITION
In the Hierarchy window, right-click on the player and 'Create Empty', to create a new
gameObject as a child inside the player, and name it “followPos”. This gameObject only has
a Transform component and nothing else.
If followPos is not inside the player, drag it inside player to make it a child of player.
transform.position = followPos.position;
Drag the followPos GameObject to the ‘Follow Pos’ value of the Player Cam script on the
camera.
Now when we play, the camera will set it's position to the position of followPos.
You can move the followPos Transform position to wherever you like it.
Instead of instantly setting the camera position, we can use Lerp to move it gradually
towards the position.
To see how Lerp works, rst we will print a value that we lerp from 0 to 100.
print(lerpValue);
Now when we play the game, we can see in the output window that lerpValue starts from 0
and changes towards 100. It changes less the closer it is, and never fully reaches it.
The lerpSpeed of 0.1 makes it take 10 seconds to almost reach it's goal. A lerpSpeed of 1
makes it take about 1 second.
Delete lerpValue.
transform.position = Vector3.Lerp(transform.position,
followPos.position,Time.deltaTime*moveSpeed);
Now when we play, the camera will Lerp towards followPos instead of instantly jumping to
the position.
In the Inspector window, you can adjust the Move Speed to whatever you like.
You may have noticed that the movement is kind of jittery. When you a ect a Camera or
Physics, you should use FixedUpdate, which has the frequency of the physics system and is
independent of the frame rate. FixedUpdate is more expensive, it uses more cpu than
Update, so generally you should keep as many calculations as possible in Update.
Open the playerCam script, move the Lerp into a xedUpdate, and use xedDeltaTime
instead of deltaTime:
void Update()
transform.LookAt(targetPos.position + targetOffset);
void FixedUpdate()
inputX = Input.GetAxis("Horizontal");
inputY = Input.GetAxis("Vertical");
Move the movement out of Update, into FixedUpdate, and use xedDeltaTime:
void FixedUpdate()
Save, and now when we play, the cube and camera move much more smoothly.
The extra section below is optional, and intended for those who purchased the Glorious
Ladybug. It is sold separately at (https://assetstore.unity.com/packages/3d/characters/
animals/insects/glorious-ladybug-246641?aid=1011lGrt)
We can indirectly control the Glorious Ladybug by controlling the player, because the
Ladybug can follow the position and rotation of the player.
CUSTOM PAC KAGE
Now let’s say we wanted to bring this work into another Unity project.
A window will show all the les that Unity thinks should be included.
Uncheck the Settings folder, so you just have the scene, Materials, and Scripts. Then click
Export.
Now this package could be imported into another project. Let’s import the ladybug into our
project.
Choose the glorious ladybug package on your hard drive. Skip to Next…
Go to Window > Asset Store and search for “Glorious Ladybug”. Or use this link (https://
assetstore.unity.com/packages/3d/characters/animals/insects/glorious-ladybug-246641?
aid=1011lGrt)
When you’ve purchased the Glorious Ladybug by Hibby Games, click ‘Open in Unity’ and it
will go to the Package Manager and to the Glorious Ladybug.
If you previously purchased the Glorious Ladybug but left the store, go to Window >
Package Manager, My Assets, and nd the Glorious Ladybug.
In the Package Manager, select the Glorious Ladybug and click ‘Download’, then ‘Import’.
Next..
The package will have been made in an older version of Unity, and was made using URP
(Universal Render Pipeline).
Choose Install/Upgrade. You will see a list of all the assets it’s going to import, import
everything.
The ladybug has a script that tells it to follow a transform position and rotation.
Press play, and select the targetTransform gameObject. Rotate and move it to see how the
ladybug follows it. We can control the ladybug by controlling its target.
go to HibbyGames > Ladybug > Prefabs, and drag the ladybug_follow_example into the
Hierarchy window.
The ladybug is a prefab. Instances of a prefab can be dragged in multiple times, and if you
edit the prefab, all the instances of it get a ected by the changes.
We want to edit this ladybug without a ecting the prefab. So right click the
ladybug_follow_example, and choose Prefab > Unpack, so the gameObject is disconnected
from the prefab.
Open the ladybug_follow_example gameObject, and drag the ladybug out so it’s not a child.
Then delete the ladybug_follow_example gameObject, so we just have the ladybug by itself.
Select the ladybug in the hierarchy, and look at the follow Position script in the Inspector
window. Target Transform is what the ladybug uses for position and rotation.
Drag our player gameObject to Target Transform, so the ladybug will use the player position
and rotation.
Select player, and in the inspector, uncheck the MeshRenderer to hide the cube. Set the cube
Y position to 0 so the ladybug will be on the ground.
If you want, you can set the camera Move Speed to 0, so it doesn’t follow, and it’s easier to
see the ladybug’s face. You could also set the camera Target Pos to the ladybug or the
ladybug’s body.
Now when we play, it’s as if we are controlling the ladybug with the arrow keys.
Press play, and you can see that there a number of animations. Press Jump and the ladybug
jumps.
In the Inspector you can see there is an On Click event that res when the button is pressed.
It has the ladybug attached, and tells the Animator to SetTrigger “jump”.
Select the ladybug and go to the Animator window. Window > Animation > Animator.
In the parameters tab, there is a “jump” trigger. It is a condition for the animation transition
that goes from “Any State” to the ladybug_jump animation.
We can set this trigger from our own script to make the ladybug jump.
if(Input.GetKeyDown(“space”))
playerAnim.SetTrigger(“jump”);
The ladybug has an Animator component on it. Select player, and drag the ladybug onto
Player Anim.
Now when you play, you can trigger the jump animation by pressing the space key.
Go to (blockadelabs.com)
Create a folder called Images, and drag your skybox image into it.
While skybox is selected, in the Inspector select the Shader and choose Skybox >
Panoramic.
Click the little circle beside the Default-Skybox material, and choose your skybox material.
Now you have a nice background, but if you look around you will notice it has a seam in it.
Select your skybox image in the Images folder, and in the inspector, uncheck “generate Mip
Maps” and press apply. The seam should be gone.
Maybe change the color of the oor material so it matches the background better.
Maybe set the camera Move Speed back to 1 so it’s easier to look around while walking.