Home > OS >  VR speedrun timer
VR speedrun timer

Time:06-16

I am working on a VR speedrun game and I need a timer. The timer doesn't need to be showed in the screen for the player, just on the map I made. It needs to start when the player (VR) passes a specific point and end when it reaches a different point. If anyone has an idea of how to make this work I would really appreciate it.

CodePudding user response:

On the start line you could have an empty gameobject with a trigger collider on it, and in the OnTriggerEnter event you could start a Coroutine that keeps track of the time, and on the finish line you'd have another trigger collider that sets a flag and stops the timer.

Something along the lines of this should work:

using UnityEngine;
using System;

public class Player : MonoBehaviour {

    private bool _isTimerStarted = false;
    private float _timeElapsed = 0;
    
    private void OnTriggerEnter(Collider other) {
        if (other.gameObject.name.Equals("Start Line")) {
            _isTimerStarted = true;
            StartCoroutine(StartTimer());
        } else if (other.gameObject.name.Equals("Finish Line") {
            _isTimerStarted = false;
        }
    }

    IEnumerator StartTimer() {
        while (_isTimerStarted) {
            _elapsedTime  = Time.deltaTime;
            yield return null;
        }
        yield break;
    }
}

For this to work just make sure your player has a RigidBody attached or else no collision will be detected :)

CodePudding user response:

If you want a "timer" as in "show the elapsed time since some event" you might take a look at Stopwatch

var sw = Stopwatch.StartNew();
...
Console.WriteLine(sw.Elapsed.ToString());

The stopwatch is primarily intended for performance measurements. But it is easy to use, so if it fits your use case you might as well make use of it, even if the resolution and accuracy is much greater than you need.

  • Related