- Home /
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");
}
}
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'...
I tried to do it. It will only work when you enter the trigger. As such, the timeee variable only increases 1 time when it is entered for the first time. I need to constantly increase the timeee.
Answer by Caeser_21 · Feb 25 at 12:14 PM
@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
Answer by f0uuu · Feb 25 at 12:24 PM
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.
Np and also thanks for letting me know... I shall change the script
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
OnTriggerStay not updating 1 Answer
Work around for onTriggerStay? 1 Answer
Call function on all objects in trigger 2 Answers