I want to pick up objects to increase timer.

I have a timer that counts down every second (which I got from a tutorial), and when it reaches 0 it’s Game Over. I want to be able to pick up objects (water) to increase the time, but don’t know how.

Image timerBar;
public float maxTime = 5f;
public float timeLeft;

public float water = 1f;

public GameManager theGameManager;

void Start()
{
    timerBar = GetComponent<Image>();
    timeLeft = maxTime;
}

void Update()
{
    if(timeLeft > 0)
    {
        timeLeft -= Time.deltaTime;
        timerBar.fillAmount = timeLeft / maxTime;
    }
    else
    {
        Time.timeScale = 0;
        Destroy(gameObject);
        theGameManager.RestartGame();
    }
}

void OnCollisionEnter2D(Collision col)
{
    if (col.gameObject.tag == "Water")
    {
        timeLeft += water;
    }
}

}

Hello @Jjeesee

Your code seems right. If is not working is because OnCollisionEnter2D() is not beeing called.

-First, I’m supose game is 2D and both player and Water have a collider2D.

-This script must be placed in the player itself, that have a collider and a rigidbody. (This collider must not be selected as Trigger: Im not 100% sure for this)

-Water element must also have a collider2D (not trigger)

-Water object must be tagged as “Water” , not “water” nor “WATER”

-Be sure colliders are realyl colliding (As its a 2D collider, you need to be sure they are all in same plane)

And i think thats all you need to make it works…
To be sure, as a good practice, aways check first if the method is beeing called, by using a Debug.Log, like this:

 void OnCollisionEnter2D(Collision col)
 {
     Debug.Log("OnCollisionEnter2D is called");
     if (col.gameObject.tag == "Water")
     {
         timeLeft += water;
     }
 }

Good luck!

Ok, I solved it! I pulled the timer script into the playercontroller in inspector, I just had to refer it. The reference wasn’t there from the beginning, but it got added once I moved part of the script to playercontroller, and then I just failed to refer it. I think that was all…

Sorry for the beginner ignorance? I appriciate all the help, thanks!!