RotX18 / MP_Group4_EscapingReality

VR Escape room game developed in Unity
3 stars 0 forks source link

Timer Feature #138

Closed RotX18 closed 2 years ago

RotX18 commented 2 years ago

Objective: Add a timer to the game to add light pressure to the player

RotX18 commented 2 years ago

Completed Timer

Timer works by counting the seconds using Time.deltaTime and incrementing the minutes by 1 every time the seconds value passes 59. and updating the float in PlayerPrefs

Code + Description

Timer.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;

public class Timer : MonoBehaviour
{
    #region PUBLIC VARS
    public TextMeshProUGUI txtTimer;
    #endregion

    #region PRIVATE VARS
    private float _minutes = 0;
    private float _seconds = 0;
    #endregion

    private void Update() {
        _seconds += Time.deltaTime;

        //updating the counter every minute
        if(_seconds > 59){
            _seconds = 0;
            _minutes += 1;
        }

        //updating the timer text in the scene
        txtTimer.text = $"{LessThanTen(_minutes)}:{LessThanTen(Mathf.Round(_seconds))}";

        //saving the current value into PlayerPrefs
        PlayerPrefs.SetFloat("minutes", _minutes);
        PlayerPrefs.SetFloat("seconds", _seconds);
    }

    private string LessThanTen(float f){ 
        //appending a "0" in front if f is less than 10
         if(f < 10){
            return $"0{f}";
        }
        else{
            return f.ToString();
        }
    }
}

Description: This script is responsible for setting the timer text in the game scene.

EndSceneTimer.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;

public class EndSceneTimer : MonoBehaviour
{
    public TextMeshProUGUI txtTimer;

    private void Start() {
        txtTimer.text = $"Completed in {LessThanTen(PlayerPrefs.GetFloat("minutes"))}min {LessThanTen(Mathf.Round(PlayerPrefs.GetFloat("seconds")))}s";
        PlayerPrefs.DeleteAll();
    }

    private string LessThanTen(float f) {
        if(f < 10) {
            return $"0{f}";
        }
        else {
            return f.ToString();
        }
    }
}

Description: This script is found in the end game screen and is used to update the completion time script andd reset the values in PlayerPrefs.

Timer works and feature is implemented, issue will be closed