Most effective way to block a method from running if it has already been ran this frame?

I have an object with “method A”, and this method is public and can be called from other scripts

I have 2 scripts that call “method A”, and sometimes, this can happen on the same frame, needlessly, since calling method A twice on the same frame do anything and its a waste of resources

what is a clean and effective way to stop this?

for example I could put a public bool “hasMethodABeenRunThisFrame”, and whenever method A is called this is set to true, and if it is true, then further calls for method A to run will be denied

Now the issue is how to get the bool “hasMethodABeenRunThisFrame” back to false, I could do this in lateupdate but it seems like a wast of resources to call this every frame, I could also setup a coroutine that at the end of the frame sets “hasMethodABeenRunThisFrame” to false, these were my ideas, none the height of optimal

would appreciate some input, this is a trivial problem, I am just trying to find the way that has the least amount of ovearhead connected with it

I would just do it the way you say above. Clearing, setting and testing a boolean is highly unlikely to ever be a performance bottleneck, especially as it sounds like this is manager of many things, so it’s unlikely you’ll have a lot of these types of things.

1 Like

You could also do this:

if(lastMethodCallFrameCount == Time.frameCount)
{
	return;
}

lastMethodCallFrameCount = Time.frameCount;

But like @Kurt-Dekker said, this is not something where you need to waste time or energy thinking about optimization. Unless you have a huge number of instances of this class, it really doesn’t matter.

1 Like