- Home /
Can I ensure all script executed within 1 frame?
The title may be ambitious because I cannot think of a better but please read the following. GUI and the execution of script by event trigger (e.g. mouse click on button) should be asynchronous (correct me if I am wrong). When I click a button, it will trigger a chain of methods to execute. Can I ensure the chain of methods execute in 1 frame? In other words, during execution of the chain of methods, can I prevent player trigger another another event? I want to ensure the methods execute once at a time.
Once of the solution of I think of is to implement a event queue but I have to rework most of my code. Is there another way to do it?
Answer by Bunny83 · Oct 12, 2015 at 12:05 PM
A frame is defined by one run through the programs main loop. Unity's scripting environment uses a single Thread, so there is nothing happening asynchronous. Everything happens sequencially. I guess you use the new UI system? When you click somewhere Unity will do a raycast to determine what got hit. It immediately calls a callback method on the object that was hit.
Since it's a single thread it's not possible that a method somehow isn't finished when the frame is finished. The definition is actually the other way round: As long as a method is executing the frame isn't finished yet.
An exception are coroutines (which however aren't methods). A coroutines object can yield it's execution so it will be resumed later. If you don't use coroutines, everything that is executed in a frame will end in the same frame.
What I mean is that: $$anonymous$$ain Loop Awake->Start->...->OnGUI When the button is Click in between, should not trigger function is call on asynchronous?
I think you mean
Awake->Start->...->OnGUI->OnGUI->OnGUI->OnGUI->...->OnGUI->OnGUI->OnGUI->OnGUI ;)
i.e OnGUI can run multiple times per frame.
Note OnGUI is the now half-legacy system.
No it will be called next frame. You can actually use the profiler to look at what is happening, record the moment when you click on your button and use the timeline to see what functions are called.
That mean if that onClick is long enough will freeze the GUI?
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Singleton design. 1 Answer
Several Questions about MVC pattern 0 Answers
Socket programming in unity 3 Answers