Search code examples
c#unity-game-enginevirtual-reality

VR speedrun timer


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.


Solution

  • 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 :)