Does your game or application in Unity use a lot of update loops that slow down performance? No need to install plug-ins or special packages, greatly increase performance for free with an update publisher in Unity. It makes you wonder why this isn’t a standard feature anyway (but that goes for a lot of things in Unity).
We’re basically going to make a SINGLE type of update loop for your entire project! As you can imagine, this will lead to a massive performance boost for your game, especially if you use a lot of scripts that implement any kind of update loop.
Understanding the issue:
What's the problem? Let’s address the issue of update loops in the first place (like Update
, FixedUpdate
, or LateUpdate
) in Unity, because it's more complex than you may think.
When you put code in an update loop to move a game object, like transform.position += new Vector3(0, 0, 1) * Time.deltaTime;
, under the hood a lot of different checks are being performed before the update loop is even validated and started. First, Unity checks if the object hasn’t been destroyed yet, then there's checks if the requirements have been met to be active at all. Even when it passes all these checks, Unity still needs to confirm that its own update method is functioning properly.
So basically, even BEFORE Unity runs the actual update loop, it’s doing all these involved computations, behavior iterations, call validations, preparing to invoke the method, verifying all the arguments and then finally running the little piece of code you wrote (which hardly is a performance issue compared to the aforementioned. Yes, this even happens with empty update methods accidentally left behind in scripts!
This slows down your project tremendously, and gets worse the more update loops you have!
When you have lots of objects that implement any update loop in Unity, you can see the problem if it needs to perform these under the hood checks constantly.
Come on!
But what can we do about it? This is yet another case where the Observer Design Pattern comes in!
The Solution:
First, we’re going to make an UpdatePublisher
that lives in the scene on its own GameObject. It holds the ONLY Update
method in the game, and it’ll notify all the other listeners when it’s called.
The observer itself is an interface, we’ll call it IUpdateObserver
:
public interface IUpdateObserver
{
void ObservedUpdate();
}