0% found this document useful (0 votes)
13 views

Final Lecture 4

- Coroutines allow functions to pause execution and resume later, making them behave asynchronously even though code is executed synchronously. This allows for time-based operations like fading or spawning objects over time. - Prefabs allow creating reusable game object templates. Instances of prefabs inherit properties and behaviors from the prefab. Changes to a prefab affect all instances. - Spawning objects involves instantiating prefabs at random positions with random properties like color. Coroutines allow spawning objects incrementally over time rather than all at once.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Final Lecture 4

- Coroutines allow functions to pause execution and resume later, making them behave asynchronously even though code is executed synchronously. This allows for time-based operations like fading or spawning objects over time. - Prefabs allow creating reusable game object templates. Instances of prefabs inherit properties and behaviors from the prefab. Changes to a prefab affect all instances. - Spawning objects involves instantiating prefabs at random positions with random properties like color. Coroutines allow spawning objects incrementally over time rather than all at once.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

Unity

Lecture 4
Coroutines
● Typical functions in Unity and C# act synchronously. This means that, when an event (like
Start) calls a function in a class, the function performs its behavior sequentially, line by line
from top to bottom, and then finally terminates at the end, returning a value. When the
function returns, the calling event will resume its execution at the next line.

● Coroutines are like functions, but they don’t seem to act that way. They act like they are
asynchronous.

● The coroutine has the ability to pause execution before it is completed entirely and return
control to Unity but then resume where it left off on the next frame. This demonstrates the
asynchronous behavior of coroutines.

● In other words, coroutines are a way of handling tasks that execute incrementally over time.
In contrast, most functions make the program wait until they finish. 2
Coroutines
● For instance, a really slow
function, which fills the
scene with 400,000 randomly
placed cubes, might take a
while to complete.

● Unity will lock up for several


seconds waiting for this
function to finish before the
game is allowed to begin.
One way to get around this is
to use a coroutine. 3
Coroutines
● Another example, consider
the task of gradually fading
from one color to another
color.

● As it stands, the function will


not have the effect you might
expect.

● One way to achieve the


desirable result is to use a
coroutine.
4
Coroutines
● Coroutines are always declared with
an IEnumerator return type, and they
always have a yield statement
somewhere in their body.

● Coroutines cannot be called like


regular functions. Instead, the
function StartCoroutine is used to or

initiate the specified coroutines.

5
Coroutines
● The yield return null line terminates
execution of the coroutine for the
current frame, but the coroutine will
resume at the next line on the next
frame.

● The yield WaitForSeconds statement


works like a sleep function. It is used or

to suspend execution of the coroutine


for some seconds before resuming on
the next line.
6
Coroutines
● When the game is started, we
don’t experience a lock, but
we do get to watch cubes fill
in the world.

● It’s a great method to start an


unusually long function and
not have to wait for its
completion before the rest of
some code is executed.

7
Coroutines
● You will notice that the loop
counter in the Fade function
maintains its correct value
over the lifetime of the
coroutine.

● In fact, any variable or


parameter will be correctly
preserved between yields.

8
Countdown Timer
● To create a countdown timer:
1) Create a GUIText GameObject in the
scene: RIGHT CLICK on Hierarchy view
and choose UI  Text-TextMeshPro.

2) Create a new C# script and name it


CountDownTimer, and attach it to an
empty Gameobject.

3) Finally, drag the Text object from


Hierarchy panel and drop it on TextTimer
TextMeshPro in the Inspector settings of
the GameObject. 9
Prefabs
● A prefab is a template of a game object that can be reused. This allows to generate many
game objects that share properties and behaviors and grouping them under a single header.

● Changes made to a prefab are reflected in all of its instances.

● Prefabs are used in two common ways:

1) When we need a large number of copies of a single element (e.g., streetlights). Once a
streetlight prefab is designed, it can be instantiated and placed in various parts of the
scene. If we decide to change the intensity of light for all the streetlights, we can modify
the prefab, and this will cause all the instances to change.

10
Prefabs
2) When we need to generate dynamic game objects. For example, we could model an
explosive shell shot from a cannon as a prefab. Each time the cannon is shot a new
prefab shell would be instantiated (through one of your scripts). In this way each new
instance of the shell will inherit all the prefabs properties, but it will have its own
location and state.

● A copy of a prefab is called an instance, instantiate is the action of creating an instance.

● To create a prefab, simply drag the GameObject from the Hierarchy view and drop it into
the Project window. This will automatically save the object as a prefab.

● Prefabs can be done manually in the visual editor or spawned by using commands in
scripts.
11
Prefabs – Brick Shooter
1) Create a Cube GameObject in the scene and name
it Brick.

2) Select the Brick GameObject in Hierarchy view 


Click Add Component in the Inspector panel 
Select Physics  Choose Rigidbody.

3) Drag the Brick GameObject from the Hierarchy


view and drop it into the Project window to save it
as a prefab.

4) Delete the Brick GameObject from the scene and


drag the prefab instead.
12
Prefabs – Brick Shooter
5) Duplicate the object multiple times until the entire wall is
completed.

6) Create a Sphere GameObject in the scene and name it


Bullet, Add a Rigidbody Component to it, save it as a
prefab, and delete it from the scene.

7) Create a new C# script and name it BrickShooter, and


attach it to the Main Camera GameObject.

8) Drag the Bullet prefab into the Projectile slot of the script.

9) Drag the Main Camera GameObject into the Shot Position


slot of the script.
13
Prefabs – Brick Shooter

14
Prefabs – Brick Shooter
● Instantiate ( Object Prefab, Vector3 Position, Quaternion Rotation )  Instantiate method
takes three parameters 1) Prefab which is a reference to object to be spawned. 2) The world
position for the new object. 3) Orientation of the new object. If position and rotation are not
specified, the GameObject is spawned at the origin (0,0,0) with zero rotation.

● The first argument, the prefab that is to be spawned, is generally a public GameObject
variable. Once the variable is declared as public, a slot will appear in the component in the
Inspector, and you can drag in a prefab that you have saved (make sure you are dragging
the prefab that is saved in the Project Panel) which is then connected to the variable and can
be instantiated.

15
Spawning/Destroying GameObjects
● In this tutorial, we will spawn a number
of spheres and cubes at random
positions and with different colors.

1) Create sphere and cube game


objects and save both objects as
prefabs in the project.

16
Spawning/Destroying GameObjects
2) Create two empty game objects named
for example:

■ Spawner: it is considered a game


manager to which we will assign
the script.

■ SpawnedObjects: it is considered a
parent game object for all objects
that will be instantiated.

17
Spawning/Destroying GameObjects
3) Create a new C#
script and name
it ObjectSpawner,
and write the
following code:

18
Spawning/Destroying GameObjects
● objectsToSpawn is an array of objects
that will contain the prefabs we wish to
spawn. Later on, we will insert the
prefabs that we have saved into this
array from the Inspector panel.

● spawnParent is the transform of the


parent object named “SpawnedObjects”
in which we will store all spawned
objects as children.

● RandomColor function creates a random


color to apply it to the spawned object. 19
Spawning/Destroying GameObjects
● Spawn function is of a type called IEnumerator. This signals to Unity that this is a co-
routine. This function contains a simple while-loop for iteratievly creating prefabs.

● In each iteration, Instantiate method creates one of the objects listed in ObjectsToSpawn
array and stored it as a child in spawnParent object. The position and rotation of the
instantiated object are specified randomly.

20
Spawning/Destroying GameObjects
● The color of the spawned object is identified randomly using RandomColor function.

● The yield command here allows us to pause the while-loop and hence limit the creation of
the prefabs to one every some seconds specified by delay.

● Spawn coroutine is called using StartCoroutine function in Unity, which is found in the
Start function of this example.

21
Spawning/Destroying GameObjects
4) Attach the C# script to the Spawner
object: select the object in the Hierarchy
panel  click the Add Component
button in the Inspector panel  choose
the ObjectSpawner script.

As can be seen, Objects To Spawn list is


empty. This list must include the
prefabs that are to be spawned. Press
the add button to add objects to the
list.
22
Spawning/Destroying GameObjects
5) To provide a connection to the objects
we wish to spawn: drag in the ball and
cube prefabs that we have saved and
drop them into Element 0 and Element
1 in Objects To Spawn list.

6) In the Inspector panel, set the wait time


and range value.

23
Spawning/Destroying GameObjects
7) To destroy the instaniated objects after
a set amount of time, create a new
script, name it DestroyingObject, and
write the following code:

8) Attach this script to the prefabs and set


the value of TimeInSeconds from the
Inspector panel. 24
Creating A New Skybox Material
● A skybox is a cube surrounding the camera with pictures of the sky on each side. No matter
what direction the camera is facing, it’s looking at a picture of the sky.

● New scenes come with a simple default skybox already assigned to them.

● Just like the brick textures, skybox images can be obtained from a variety of websites (search
for skybox textures).

● For creating a new skybox material:

1) Create a new material: either right-click and choose Create, or choose Create from the
Assets menu.

2) Select that material to see its settings in the Inspector.


25
Creating A New Skybox Material
3) Change the shader used by this material: new
materials are set to the Standard shader by
default. Click the menu to see the drop-down list
of all the available shaders. Select the Skybox
section and choose 6 Sided in the submenu. With
this shader active, the material now has six large
texture slots. These six texture slots correspond to
the six sides of a cube, so these images should
match up at the edges to appear seamless.

26
Creating A New Skybox Material
4) Import the skybox images into Unity: drag the
files into the Project view or right-click in Project
and select Import New Asset.
Up Down

Right Left

27
Front Back
Creating A New Skybox Material
5) Click the imported texture to see its properties in the Inspector and
change the Wrap Mode setting to Clamp and click Apply.
Ordinarily, textures can be tiled repeatedly over a surface, and for
this to appear seamless, opposite edges of the image bleed together.
But this blending of edges can create faint lines in the sky where
images meet, so the Clamp setting will limit the boundaries of the
texture and get rid of this blending.

28
Creating A New Skybox Material
6) Drag these images to the texture slots of the
skybox material. The image names correspond to
the texture slot to assign them to (such as left or
front). Once all six textures are linked up, you can
use this new material as the skybox for the scene.

29
Creating A New Skybox Material
7) Open the lighting window:
Window  Rendering 
Lighting.

8) Switch to the Environment tab


and then set this new material
to the Skybox Material slot;
either drag the material to that
slot, or click the tiny circle icon
to bring up a file picker.

9) Click Play to see the new


skybox. 30
Level Changing
● To load a different level (or Scene) in Unity, the following command is used:

or

where LevelName/LevelID is the name/ID of the level to load.

● The Application class is a special class used to access and control runtime data, like whether
to quit the game or load a specific scene.

● Before we can load a level we have to add it to the list of levels used in the game. Use File 
Build Settings  Add Open Scenes.

31
Level Changing
● Scene files can be dragged and dropped from the Project panel into the levels list.

● We can also rearrange the order of scene files within the list by dragging and dropping
items.

● Each level is assigned a unique number or ID, shown in the right-hand column. This ID can
be passed to the LoadLevel function to load the appropriate level.

32
Level Changing
● In this tutorial, we will create two different scenes. The first scene is considered the main
menu of the game which contains a button Start, while the second scene can be any other
scenes (e.g., the starting scene). When the player click on the start button, he/she is directed
to the starting scene.

Main Menu Scene Starting Scene


33
Level Changing
1) Create a new scene named MainMenuScene and
create a Button object in this scene.

2) Create a new C# script and name it LevelChanging


and create OnButtonClick() method in this script.

3) Create an empty GameObject in the scene named


GameManager to attach the script to.

4) Select the Button and add an OnClick event in the


button component.

5) Drag the created GameManager object to the


OnClick event and select the OnButtonClick()
34
method we created.
Camera following with LookAt()
● LookAt(Transform target);

● LookAt method is used to make a GameObject’s (not


just cameras) forword direction point at the transform
of another object, where target is object to point
towards.

1) Create a new C# script and name it


FollowingObject, and attach it to the Main Camera.

2) Drag the target GameObject from Hierarchy panel


and drop it on in the Inspector settings of the Main
Camera.
35
Local vs Global Coordinate Space
● Every single object has its own origin
point, as well as its own direction for
the three axes, and this coordinate
system moves around with the object.
This is referred to as local
coordinates.

● The overall 3D scene also has its own


origin point and its own direction for
the three axes, and this coordinate
system never moves. This is referred
to as global coordinates. 36
Local vs Global Coordinate Space

World
Local

37
Local vs Global Coordinate Space

Note: By default, the Rotate()


and Translate methods
operate on local coordinates.

World
Local

38

You might also like