Timer in C# Script

Greetings all!

I am developing a game that uses a script to measure the amount of time it took for the player to complete a level. The code I currently have does that, but it does not display the time updating every second and only displays the updated time every time a player picks up one of the level’s pickup objects.

I would like to have the timer display the time as it updates every second in real time (or half second if it can be done).

The code is attached below. I believe the problem lies in the Timer() or the SetCountText() function, so I recommend checking those places.

Thanks in advance!

2658418–187446–PlayerController.cs (1.63 KB)

You call SetCountText in wrong place…It happens only on collisions

Call to the SetCount() after the time+=1 should solve your issue.

private IEnumerator Timer() {
while (true) {
yield return new WaitForSeconds(1);
time += 1;
SetCountText();
}
}

1 Like

You should use some sort of step counter to update the text every so often in fixed update probably. Basically have an integer like “stepsRemaining = 50;” and in your FixedUpdate () method, subtract one from it until it hits zero, then do an update to the text object, and reset the step counter, rinse and repeat.

Edit: the answer above may be easier actually.

void Update() {
timer += time.DeltaTime;
SetCountText();
}
3 Likes

I like the simplicity of your answer, although updating the counter every update might be a bit overkill. Ideally it should only happen every N amount of frames so it doesn’t needlessly update every fraction of a second, costing extra overhead. Still though that would work like, right away that way.

Check this Unity - Scripting API: Time.time

For something so simple it might actully cost more to add a conditional than it would to just update it every frame. Besides this is a micro optimization that can be dealt if and when it becomes a problem.

It would certainly be faster to reduce an integer for counting down frames between updates than it would be to simply update it every frame wouldn’t it? I mean that’s the difference between assigning a variable and causing uGui to redraw that object, vrs just saying someInt–; instead… if it is slower I’d be surprised! Especially since I been doing crap like that forever haha

yeah i wasnt thinking about the updating of the UI text, so you would be right