Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Timer & on Trigger Events 2D

Discussion in 'Scripting' started by GrimothyUA, May 6, 2020.

  1. GrimothyUA

    GrimothyUA

    Joined:
    Dec 9, 2019
    Posts:
    2
    Hello , I am new to unity & C# .

    I am working on a 2D game that is time based per level.

    I do not seem to have any obvious errors in visual studio.

    A)The starting time updates as it should

    B)Debug .Log shows that the trigger is activated.

    Problem is the time does not count down after the player moves through my trigger , please help :(


    What needs to happen is :

    The Game starts , the time is shown but does not start yet.

    When the Player goes through a trigger (Starting Door for example) , after that the time counts down.

    When the player reaches the exit the timer needs to stop (I have not yet started with the coding for the exit).


    Here is what I have so far:



    using System.Collections;
    using System.Collections.Generic;
    using System.Threading;
    using UnityEngine;
    using UnityEngine.Experimental.PlayerLoop;
    using UnityEngine.UI;

    public class StartTimer : MonoBehaviour
    {
    float currentTime = 0f;
    float startingTime = 120f;



    public Text countdownText;


    void Start()
    {
    currentTime = startingTime;
    countdownText.text = currentTime.ToString("0");
    }

    void OnTriggerEnter2D(Collider2D other)
    {
    if (other.name == "player")

    {
    Debug.Log("Start Timer");
    Update();

    }

    void Update()

    {

    currentTime -= 1 * Time.deltaTime;
    countdownText.text = currentTime.ToString("0");

    if (currentTime <= 0)

    {

    currentTime = 0;

    }

    }
    }
    }

    __________________________________________________________________________________

    I hope this makes sense , thank you in advance :)
     
  2. Antistone

    Antistone

    Joined:
    Feb 22, 2014
    Posts:
    2,835
    Please use code tags.

    Update() is a magic method that automatically runs every frame. You shouldn't call it explicitly like you are doing inside your OnTriggerEnter2D method. Instead, have the collision set a variable, and have Update check that variable to decide how it should act. (But remember Update will always run, whether the trigger has happened or not.)

    But if that were your only problem, you'd see the timer running all the time, instead of not running at all. I think you have a problem with your curly braces {}, but it's hard to tell because you didn't use code tags.
     
  3. GrimothyUA

    GrimothyUA

    Joined:
    Dec 9, 2019
    Posts:
    2
    Thank you very much for your help Antistone