- Home /
OnTriggerStay execution script time can last more than 1 frame?
I have a simple but an important question.
Imagine that i have this script attached to any gameobject where the OnTriggerStay expend much time executing the code:
void OnTriggerStay (Collider other)
{
for (int i = 0; i < 100000; i++)
{
GameObject gameObj = GameObject.FindGameObjectWithTag ("anyTag");
}
}
Is it possible that the execution time of script inside the OnTriggerStay can last more than the time between one frame and the nextone? How can I check it?
hex has already said that it can't, but are you asking because you're curious or because you want it to?
Because i want to know if it something that i need to keep in $$anonymous$$d.
Answer by hexagonius · Feb 07, 2018 at 09:23 PM
Simply, it can't. you could just log within update and fixedupdate and see that they're alternating. it's possible that there's multiple fixedupdates between frame updates or none at all, but you won't get a long executing OnTriggerStay to be bypassed by update. it's the same thread.
Answer by Nimosh · Dec 28, 2021 at 01:58 AM
You can use courutines to do task that takes more that one frame.
Your answer should be more specific that this. void OnTriggerStay () => StartCoroutine("MyCoroutine");
is hardly a practical solution.
Very specific but somewhat reductio-ad-absurdum-question isn't helpful, I agree.
Answer by endasil_unity · Dec 28, 2021 at 11:45 AM
You will stay on the same frame until the code in OnTriggerStay is done. Something that is important to understand is that the code execution is linear in Unity by default. If you have some code that takes a long time nothing else will be done until that code is complete. If your code in OnTriggerStay would take 30 seconds to complete, your game will freeze for 30 seconds.
If you want to perform tasks that take a lot of time and perform them over multiple frames, coroutines are a good thing to look at. You would perform a part of the task and then do a yield return to continue on the next frame.
Here you can read up on coroutines if you're curious. https://docs.unity3d.com/Manual/Coroutines.html
Your answer
Follow this Question
Related Questions
How to stop an Object from Moving When It Hits Collider 2 Answers
OnTriggerStay2D working only when player ISN'T moving 2 Answers
Ontrigger if 2 Answers
Layermask for OnTriggerStay 2 Answers
Alternative to OnTriggerStay2D 1 Answer