You are on page 1of 27

##############

##############

AARON HIBBERD
U N I T Y 101
SECOND EDITION
###########
###########

Setup ..............................................................................................................3

Start a New Project ...................................................................................................4


Scene Setup .............................................................................................................5
Look Around .............................................................................................................6
Player Script ...................................................................................................7

Update Loop ............................................................................................................8


Delta Time ................................................................................................................9
Translate .................................................................................................................10
Public Variable ........................................................................................................11
Input Manager ........................................................................................................12
Move the Cube .......................................................................................................13
Rotate ....................................................................................................................14
Inverse Transform Direction ......................................................................................15
Camera Script ...............................................................................................16

Look at Position .......................................................................................................17


Target Offset ...........................................................................................................18
Follow Position ........................................................................................................19
Lerp .......................................................................................................................20
Fixed Update ..........................................................................................................21
Fixed Deltatime .......................................................................................................22
Extra ............................................................................................................23

Custom Package .....................................................................................................24


Glorious Ladybug ...................................................................................................25
Jump Animation ......................................................................................................26
Skybox ...................................................................................................................27
SETUP

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

Download Unity Hub (https://unity3d.com/get-unity/download)

Install the newest LTS version of Unity, and Visual Studio.

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.

You can drag the windows to arrange them as you like.

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.

Name the cube “player".

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.

In the Hierarchy, Create, 3D Object, Plane, and name it “ oor”.

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.

In Project, create a new folder, and call it Materials.

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.

Hold the right mouse button and move to look around.

While still holding the right mouse button, you can use the WSAD keys to move.

Hold the middle mouse button and drag to pan around

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.

Select the Main Camera in the Hierarchy.

Game Object > Align with view.

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 .

Don’t forget to save, File > Save.


ff
P L AY E R S C R I P T

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

In Project, create a Folder and name it “scripts".

Create a C# Script, before pressing enter, name it “player”.

Wait a moment for Unity to nish compiling the new script.

Double click to open the script in Visual Studio.

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.

There is an Update() this will repeatedly loop again every frame.

The speed of Update will uctuate with the frame rate of the game.

In the Start() put:

print("this happens once");

In the Update() put:

print("this repeats every frame");

Save the script.

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.

The Console window will show our print messages.

Press play and see in the Console window how our code in the update loop happens every
frame.

Don’t forget to save, File > Save.


fl
fi
fi
fi
fi
DELTA TIME

Replace the Update print with:

print(Time.time);

Save the script and go back to Unity.

Press Play, you can see the time since the game started running.

Stop and go back to the script.

Replace the Update print with:

print(Time.deltaTime);

Save the script and go back to Unity.

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

Select the player gameObject, and look at the Inspector window.

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.

Replace the Update print with:

transform.Translate(0.01f,0f,0f);

We are going to the transform component on this gameObject, and using Translate to add to
the positions.

It takes a Vector3, a Vector 3 has 3 numbers to represent a position in 3D space, X, Y, and Z.

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 f after the number means it's a oat.

A oat is a number with decimals.

If there's no f then it's an integer, which is a whole number without decimals.

Save that and wait for it to compile.

Now when we press play, the player moves.


fl
fi
fl
P U B L I C VA R I A B L E

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.

Update the script to:

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.

Above Start, add:

public oat speed = 2f;

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.

Update the script to:

transform.Translate(speed * Time.deltaTime,0f,0f);

Save the script.

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.

Don’t forget to save, File > Save.


fl
ff
ff
INPUT MANAGER

Go to Edit > Project Settings, Input Manager.

Open the Axes.

There should be a list of inputs, including Horizontal, Vertical, and Jump.

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".

And the same with “Vertical”.

These are the names we are going to reference.

You can see they have positive and negative buttons, they are a ected by the Arrow or
WASD keys.

Go back to the player script.

In the bottom of the Update() add:

print("horizontal "+Input.GetAxis("Horizontal"));

print("vertical " + Input.GetAxis("Vertical"));

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.

Inside the Update():

oat inputX = Input.GetAxis("Horizontal");

oat inputY = Input.GetAxis("Vertical");

transform.Translate(speed * Time.deltaTime* inputX, 0f, speed * Time.deltaTime*


inputY);

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.

Inside the Start():

//print("this happens once");

Now when you play the game, you can move the cube with the arrow keys.

Don’t forget to save, File > Save.


fl
fl
ROTATE

Rotate works much the same as Translate, lets make it rotate with the same controls.

At the top of the player script under speed:

public oat turnSpeed = 100f;

Inside the Update(), copy paste the Translate line, and comment out the old line.

Replace “Translate” with “Rotate”, and replace “speed” with “turnSpeed”.

//transform.Translate(speed * Time.deltaTime* inputX, 0f, speed * Time.deltaTime*


inputY);

transform.Rotate(turnSpeed * Time.deltaTime * inputX, 0f, turnSpeed *


Time.deltaTime * inputY);

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.

So we want to use inputX to rotate on the Y-axis.

Replace the rotate line with:

transform.Rotate(0f, turnSpeed * Time.deltaTime * inputX, 0f);

Now when we play, it turns left and 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:

transform.Translate(speed * Time.deltaTime * inputY *


transform.InverseTransformDirection(transform.forward));

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.

Don’t forget to save, File > Save.


ff
CAMERA SCRIPT

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

Now lets make a script for the camera.

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"

Above the Start() add:

public Transform targetPos;

Inside Update() add:

transform.LookAt(targetPos.position);

Save, and attach this script to the Main Camera.

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.

Don’t forget to save, File > Save.


fi
TARGET OFFSET

We can o set the position the camera looks at by adding a Vector3.

Open the playerCam script and add:

public Vector3 targetOffset;

And in Update() change the lookAt to:

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

Next let's make the camera follow the player.

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.

In the inspector, move it to a good position for the Camera to be.

I set the position to 0,2,-3.5.

Open the playerCam script.

At the top add:

public Transform followPos;

Inside Update() add:

transform.position = followPos.position;

Save, go back to Unity, and wait for the script to compile.

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.

Don’t forget to save, File > Save.


LERP

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.

At the top of the playerCam script add:

public oat lerpSpeed = 0.1f;

private oat lerpValue = 0f;

In the update() add:

lerpValue = Mathf.Lerp(lerpValue, 100f, Time.deltaTime * lerpSpeed);

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.

Replace lerpSpeed with moveSpeed:

public oat moveSpeed = 1f;

Inside Update(), delete the lerp value and print lines.

Replace the position update with:

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.

Don’t forget to save, File > Save.


fl
fl
fl
fi
FIXED UPDATE

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()

transform.position = Vector3.Lerp(transform.position, followPos.position,


Time. xedDeltaTime * moveSpeed);

Save the playerCam script, and open the player script.


fi
fi
ff
fi
FIXED DELTATIME

In the player script, at the top add:

private oat inputX = 0f;

private oat inputY = 0f;

In Update() change the input lines to:

inputX = Input.GetAxis("Horizontal");

inputY = Input.GetAxis("Vertical");

Move the movement out of Update, into FixedUpdate, and use xedDeltaTime:

void FixedUpdate()

transform.Translate(speed * Time. xedDeltaTime * inputY *


transform.InverseTransformDirection(transform.forward));

transform.Rotate(0f, turnSpeed * Time. xedDeltaTime * inputX, 0f);

Save, and now when we play, the cube and camera move much more smoothly.

Don’t forget to save, File > Save.

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)

USE THIS SPECIAL LINK FOR 50% OFF!


( H T T P S : / / H I B BYGA M E S . I T C H . I O /G LO R I O U S )
fl
fl
fi
fi
fi
EXTRA

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.

In the Project window, right click level01 > Export Package.

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.

If you received the Glorious Ladybug as a .unitypackage le:

Go to Assets > Import Package > Custom Package.

Choose the glorious ladybug package on your hard drive. Skip to Next…

If you need to buy it from the Unity Asset Store:

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.

Now there is a HibbyGames folder added to the project.


fi
fi
fi
G LO R I O U S L A DY B U G

Go to HibbyGames > Ladybug > Scenes, and open EXAMPLE_follow_position_1.

When it asks, import TMP Essentials, this is for ui text.

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.

Stop playing and go back to level01.

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.

Don’t forget to save, File > Save.


ff
ff
JUMP ANIMATION

Go to HibbyGames > Ladybug > Scenes, and open EXAMPLE_animations.

Press play, and you can see that there a number of animations. Press Jump and the ladybug
jumps.

In the heirarchy, open Canvas and select btnJump.

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.

Go back to level01 and open the player script.

At the top add:

public Animator playerAnim;

in the Update Add:

if(Input.GetKeyDown(“space”))

playerAnim.SetTrigger(“jump”);

Save and go back to Unity.

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.

Don’t forget to save, File > Save.


fi
SKYBOX

Let’s also add a background.

Go to (blockadelabs.com)

Generate a skybox image and download it.

Create a folder called Images, and drag your skybox image into it.

In the Materials folder, create a new Material and call it “skybox”.

While skybox is selected, in the Inspector select the Shader and choose Skybox >
Panoramic.

Drag your skybox image onto the Spherical (HDR) Texture.

Go to Window > Rendering > Lighting, Environment.

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.

Don’t forget to save, File > Save.

GREAT JOB! THIS CONCLUDES EVERY THIN G!


fl

You might also like