- Home /
run function once per frame
I have a scene that contains ~100 objects with the same script. each script contains a function that takes about .01 seconds to execute. I need the function to execute for every object, but not all at once, so that the framerate isn't murdered. how would i make the objects execute the same function gradually, so that if object A calls a certain function, object B cannot call that same function in the same frame?
sorry if that's confusing.
Answer by ScroodgeM · Aug 06, 2012 at 09:25 PM
solution 1
in each script, add a random framesToSkip value:int framesToSkip void Start() { framesToSkip = UnityEngine.Random.Range(0, 50); } void Update() { if (framesToSkip > 0) { frameToSkip--; } else { ....do your job framesToSkip = 50; } }this will run once in 50 frames. initialization in start needs so that objects will not do job all at once
solution 2
store all objects on some other empty object with a single script that calls "DoJob()" function on objects with shedule you need
solution 3
use coroutines to make pause you need
All good ideas. solution 4: keep a centralized frame counter and then check if (frame + objectindex) % objectcount == 0, then run the function, otherwise don't. This is ALU work that doesn't really need to be done. solution 5: put all objects into an IEnumerable. Each frame, somewhere central, maintain an IEnumerator of that. Pick the next object and run its function. If the enumerator is finished, restart it. This is more like a queue and also has overhead, but hardly any ALU.
Answer by IphStich · Jun 30, 2015 at 10:59 PM
I can think of two very clean methods of doing it:
static int FrameCounter=1;
int myCounter;
void Awake () // Start works as well, but I prefer Awake
{
myCounter = FrameCounter++;
}
void Update ()
{
if (--myCounter == 0) // Works in the order they're created
{
// Call Function
}
}
Or alternatively:
static bool CanCall = true;
bool HasCalled = false;
void Update ()
{
if (CanCall && !HasCalled) // Whichever instance calls this first gets it first
{
CanCall = false;
HasCalled = true;
// Call Function
}
}
void LateUpdate ()
{
CanCall = true;
}
Both methods use a combination of static and instance variables to keep track of who should call what when.
Your answer
Follow this Question
Related Questions
Is it worth making tons of similiar methods or create big one that connects things together? 2 Answers
How to debug effectively in release mode? 1 Answer
Refreshrates and vsyncCount, what code should be applied? 0 Answers
Raycast consuming too much ! (VR) 2 Answers
Why is there a 60 fps limit for a PC-Mac build from 2019 onward? 0 Answers