Events manager

In this tutorial

the author uses “if (!eventManager)” in the instance property of the EventManager class - what exactly does this do? It seems to tell whether there is an instance of the EventManager class attached to some object in the scene, but I have no idea why it does that, and whether that’s all it does. I would have at least understood if it was “(!EventManager)”, but given that eventManager is a static field variable, I have no idea what it does.

Second, I would also like to ask why we would even do the event manager like this - why not just make the whole class static? After some googling it seems to have something to do with using the concept of a singleton - which I guess is something close to a purely static object, but in addition, it’s still something that can be treated as an instance of a class. So it’s something that’s an instance, but at the same time we use some tricks to make it behave like a static? Do I have the right (though vague) idea?

It simply checks if eventManager is null or not.
if (eventManager)
is basically the same as writing
if (eventManager != null)

EventManager is a singleton, just like you suspected. Generally in a singleton, when the instance is accessed from outside you have to check and see if your instance has been allocated first (in this case it has to be “found” actually).

In an ordinary class you can just use the keyword “this” and that will give you a reference to it’s own instance, but that does not work in a singleton because that property is static. So instead, the author goes through this extra step of using FindObjectsOfType to get a reference to the instance. The author stores this reference in a variable called eventManager.

Whenever I access the “instance” property from outside the EventManager class it’s simply going to return the reference to the instance that’s stored in the eventManager variable, except for the first time- In that case eventManager is null. It will find the reference first, store it in eventManager, and then return it.

Thanks for the explanation!