0
\$\begingroup\$

I'm pretty new to Unity, and I am trying to enable a BoxCollider from another object when the timer reaches 0, using this code:

using UnityEngine;

public class Testv2 : MonoBehaviour
{
    public GameObject otherGameObject;

    private BoxCollider Target;
    public float timeLeft = 30.0f;

    void Awake()
    {
        Target = otherGameObject.GetComponent<BoxCollider>();
    }

    void OnMouseDown()
    {
      timeLeft -= Time.deltaTime;
    }

    void Update()
    {
        if (timeLeft < 0)
        {
            Target.enabled = true;
        }
    }
}

My issue is that the timer won't go down unless I keep clicking on the object. How do I enable the timer to start when someone clicks an object, and start counting down?

\$\endgroup\$
0

1 Answer 1

0
\$\begingroup\$

Your problem derives from counting down in the OnMouseDown() method. Let's take a look at the API:

MonoBehaviour.OnMouseDown()

OnMouseDown is called when the user has pressed the mouse button while over the GUIElement or Collider.

- MonoBehaviour.OnMouseDown() @ Unity API Reference

This means that you make a call to this method when you press the mouse button. Your logic performs one increment on the timer, and that is it. In the next frame, you are still holding the mouse button, but you have not pressed the mouse button - it was already pressed! As a result, the method does not call. For future reference, regarding input, there is a clear distinction between pressing a button, holding a button and releasing a button. That is irrelevant, for now. You do not want to have to continue holding your mouse button in order for your timer to work - you want it to just work straight away.


Instead of using this method to count down, you want to use this method to start counting down. We can easily do that by setting a bool to determine if we are currently counting down, and performing the count down in the Update method.

using UnityEngine;

public class Testv2 : MonoBehaviour
{
    public GameObject otherGameObject;

    private BoxCollider Target;
    public float timeLeft = 30.0f;

    private bool countingDown = false;

    void Awake()
    {
        Target = otherGameObject.GetComponent<BoxCollider>();
    }

    void OnMouseDown()
    {
        countingDown = true;
        
        // If you want to be able to stop the timer by clicking the 
        // button again, replace the above line with
        // countingDown = !countingDown
    }

    void Update()
    {
        if(countingDown)
        {
             timeLeft -= Time.deltaTime;
        }
        if (timeLeft < 0)
        {
            Target.enabled = true;
        }
    }
}
\$\endgroup\$
1
  • \$\begingroup\$ Very informative and helpful, this worked great, I appreciate your help, thank you very much! \$\endgroup\$
    – lovelyleon
    Apr 23, 2017 at 15:39

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .