How can I add time to a timer?

Hello everyone,

I have a question regarding my timer script. The timer should count down from 20 seconds to 0. When second zero is reached, the restart function should be called.

So far so good. Everything works.

Now I have distributed objects on the map, which should add 5 seconds to the timer when they are collected.

I have assigned the entire script to the collection objects.

I have now tried several times and can’t get it to work.

Attached is the script, maybe someone can help.

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

public class Timer : MonoBehaviour
{
    public bool runningTimer;
    public float currentTime;
    public float maxTime = 25;

    public HealthSystem healthsystem;

    public Text timerText;


    // Start is called before the first frame update
    void Start()
    {
        currentTime = maxTime;
        runningTimer = true;
    }

    // Update is called once per frame
    void Update()
    {
        if (runningTimer)
        {
            currentTime -= Time.deltaTime;
            timerText.text = "Time: " + System.Math.Round(currentTime,0);
            Debug.Log(currentTime);

                if (currentTime <= 0)
                {
                    runningTimer = false;
                    healthsystem.RespawnPlayer();
                    Restart();
                }
        }
    }

    private void OnTriggerEnter2D(Collider2D other)
    {
        if (other.gameObject.tag == "Player")
        {
            currentTime += 5f;
            Debug.Log("Plus 5 Sekunden");
            Destroy(gameObject);
        }
    }

    public void Restart()
    {
        currentTime = maxTime;
        runningTimer = true;
    }
}

.
The error should be in line 46. The debug.log and destroy functions are executed.

Maybe someone can help. Greetings

Because you only want a single timer there should only be a single instance of the script running. Instead of placing the script on all the collection objects you can place it on the player and replace the trigger event with something like:

    private void OnTriggerEnter2D(Collider2D other)
    {
        if (other.gameObject.tag == "CollectionObject") // have we collected an object?
        {
            currentTime += 5f;
            Debug.Log("Plus 5 Sekunden");
            Destroy(other.gameObject); // destroy the collected object
        }
    }
1 Like

Wow, that was quick. Thank you very much, it worked straight away.

Best regards

thank you so much! It worked perfectly right away.