I'm trying to count the time any object touches the trigger.

private void OnTriggerStay2D(Collider2D collision)
{
timeee += Time.deltaTime;
}
private void OnTriggerExit2D(Collider2D collision)
{
timeee = 0;
}
What I am trying to do is; incrementing the timeee variable every second until any object starts touching the trigger until it stops touching. And when it’s 7 seconds to finish the game. I wrote the code as in the picture. However, the code starts counting but stops counting after a while.

void Update()
    {
        if (timeee > 7)
        {
            SceneManager.LoadScene("GameOver1");
        }
    }

[193100-adsız.png|193100]

As you can see, it touches the trigger, but the timeee variable does not increase after a point. When another object touches it, it starts to increase again.

I think instead of ‘OnTriggerStay2D’, you should use ‘OnTriggerEnter2D’…

@f0uuu You can try this :

  1. Create a new private bool called “IsInRange”

    private void OnTriggerStay2D(Collider2D collision) //You can also use OnTriggerEnter2D
    {
    IsInRange = true;
    }
    private void OnTriggerExit2D(Collider2D collision)
    {
    IsInRange = false;
    timeee = 0;
    }
    Then,

    void Update()
    {
    if (IsInRange)
    {
    timeee += Time.deltaTime;
    }
    else
    {
    //you can also set ‘timeee’ to 0 here
    }

          if (timeee > 7)
          {![alt text][1]
               SceneManager.LoadScene("GameOver1");
          }
      }
    

Thanks to @f0uuu for pointing out an issue with the script

Thanks, I got it. But we need to set timeee to 0. It worked when I wrote it like this:

void Update()
    {
        if (isInRange)
        {
            timeee += Time.deltaTime;
        }
        else
        {
            timeee = 0;
        }

        if (timeee > 7)
        {
               SceneManager.LoadScene("GameOver1");
        }
    }

Thanks again.