Search code examples
c#unity-game-enginetimercountdownsubtraction

Subtracting Time From Timer In Unity Game C#


Recently, I've been working on a racing game that requires the player to avoid Radioactive Barrels that should subtract 15 seconds if they happen to collide into them; Below is code for my 'Timer' script, and my Barrel Collision Script.

Timer Script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
 
public class Timer : MonoBehaviour
{
    public float timeRemaining = 10;
    public bool timerIsRunning = false;
    public Text timeText;
 
    public void Start()
    {
        // Starts the timer automatically
        timerIsRunning = true;
    }
 
    public void Update()
    {
        if (timerIsRunning)
        {
            if (timeRemaining > 0)
            {
                timeRemaining -= Time.deltaTime;
                DisplayTime(timeRemaining);
            }
            else
            {
                Debug.Log("Time has run out!");
                timeRemaining = 0;
                timerIsRunning = false;
            }
        }
    }
 
    public void DisplayTime(float timeToDisplay)
    {
        timeToDisplay += 1;
 
        float minutes = Mathf.FloorToInt(timeToDisplay / 60); 
        float seconds = Mathf.FloorToInt(timeToDisplay % 60);

        timeText.text = string.Format("{0:00}:{1:00}", minutes, seconds);
    }
}

Next, is my Barrel Collision Script:

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

public class ExplosionTrigger : MonoBehaviour 
{
  
    public AudioSource ExplosionSound;
    public ParticleSystem Explosion;
 
    public void OnTriggerEnter(Collider collider)
    {
        Explosion.Play();
        ExplosionSound.Play();
        Timer.timeRemaining += 1.0f;      
    }  
}

Is there anyway I could subtract time by colliding into said Barrels from the Timer script?


Solution

  • The easiest way to get the timeRemaining exposed to other classes is using the static keyword.

    public static float timeRemaining = 10;

    By making the variable static, it can be referenced by other classes. If you would rather not expose the variable completely, you can make static setter/getters. The variable would then be private static float timeRemaining = 10; when using the setter/getter.

    public static float TimeRemaining
    {
         get{ return timeRemaining;}
         set { timeRemaining = value;}
    }
    

    If you happen to want to expose more variables or methods to your classes from a script, I would recommend either implementing the Singleton Pattern or possibly implement your own Event System which uses the Singleton Pattern to pass events freely in your project. That way, you can subscribe and fire events for various scripts to listen for.