So I want to make a timer powerup, I have the timer script already done but I don’t know to make it pause for 3 seconds when colliding with an object, then we that 3 seconds is up the timer obviously resumes.
Script works fine just want some code that can do what I explained. Would really appreciate it!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class Timer : MonoBehaviour
{
public TMP_Text timerText;
public float startTime;
private void Start()
{
startTime = Time.time;
}
void Update()
{
float t = Time.time - startTime;
string minutes = ((int)t / 60).ToString();
string seconds = (t % 60).ToString("f2");
timerText.text = minutes + ":" + seconds;
}
}
Here one solution, based on your code.
We keep track of a cooldown timer, which we can reset by calling AddCooldown() .
Then we only keep counting with the “main timer”, when there is currently no cooldown applied.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class MyTimer : MonoBehaviour
{
[Header("Timer in m:s")]
[Tooltip("Time elapsed since game start")]
[SerializeField] private string timeElapsed;
private float startTime;
[Header("Cooldown in s")]
[Tooltip("Time in seconds for which the timer stops counting")]
[SerializeField] private float cooldown = 3f;
private float cooldownTimer;
private void Start()
{
startTime = Time.time;
// Makes sure the cooldown does not stop the main timer right after start
cooldownTimer = cooldown;
}
void Update()
{
// For Testing. Press V to pause the Timer for 3 seconds
if (Input.GetKeyDown(KeyCode.V))
{
AddColldown();
}
// Count time since AddCooldown() was triggered
cooldownTimer += Time.deltaTime;
// Lets the main timer only count, if there is no cooldown running
if (cooldownTimer >= cooldown)
{
float t = Time.time - startTime;
string minutes = ((int)t / 60).ToString();
string seconds = (t % 60).ToString("f2");
timeElapsed = minutes + ":" + seconds;
}
}
private void AddColldown()
{
cooldownTimer = 0f;
}
}