Time

Open S0301 starter project. Create a new 3D project and add the starter package to the project.

Update(): Runs once per frame. Time elapsed depends on the Operating System, current system load, hardware, etc. Not consistent.

LateUpdate(): Runs once per frame but starts after AnimationUpdate is completed.

FixedUpdate(): Runs multiple times per frame

GUIUpdate(): Runs multiple times per frame

Check docs.unity3d.com/Manual/ExecutionOrder.html for more details.

In the new project, we will examine Update(), LateUpdate(), FixedUpdate() and also one more approach.

Open Time scene, which can be found under assets folder. When you open the scene, you can find 4 Adams.

Each of the Adams are associated with a different script and use a different Update function.

First, open Update Move script. There is an Update function but empty. We want the character to move towards the Z axis.

Add the following code to the Update function:

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

Save and run. UpdateAdam moves forward but the others are not.

Copy the same code to FixedUpdate() for FixedAdam and LateUpdate() for LateAdam.

Save and test. FixedAdam is moving faster than others because FixedUpdate is called multiple times per frame.

When you run the same scripts on different computers, they run with different speeds and there will 

be no consistency in terms of their speed.

Update SecondsAdam's update function now.

Add a few variables:

float timeStartOffset = 0;

bool gotStartTime = false;

Modify Update function.

if (!gotStartTime) {

gotStartTime = true;

timeStartOffset = Time.realtimeSinceStartup;

}

this.transform.position = new Vector3(this.transform.position.x,

this.transform.position.y,

Time.realtimeSinceStartup - timeStartOffset);

Save and test. This character will move meters per second. No matter which computer you use, it is going

to run at the same rate.

Open UpdateMove script of UpdateAdam and change 

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

to

this.transform.Translate(0, 0, Time.deltaTime);

Save and run. SecondsAdam and UpdateAdam moves exactly at the same rate. The other two are getting behind

based on how often they get updated.

Modify FixedUpdate() and LateUpdate() as follows:

this.transform.Translate(0, 0, Time.deltaTime);

Save and run. now all Adams move at the same speed.

Challenge: How can we set the speed in these functions?

Solution: Define a variable for speed

public float speed = 0.5f;

void Update() {

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

}

do the same modification for all.

Save and test.

If you have rotation like the tank game, you can use Time.deltaTime to have a consistent rotation speed.

StatusPrototype
CategoryOther
PlatformsHTML5
Authorfulminare
Made withUnity

Leave a comment

Log in with itch.io to leave a comment.