How to Instantiate Event Manager before all other objects

Hi,

I know there is going to be a simple answer for this one, but I don’t seem to be able to find it for myself.

I’ve just started using Unities event system for the first time and I’ve got it all set up and working just fine.

Except for objects that are already in the project at run time. They throw up a NullReferenceException when they try to subscribe to my Event Manager.

If the object is instantiated during runtime it can call the EventManager no problems, so it must be down to the order of instantiation. The objects are looking for the EventManager before it exists.

I’m assuming there is work around for this, other than instantiating everything during runtime.

Thanks in advance for any help

Sounds like a defective singleton implementation to me! Here’s the correct way:

Simple Unity3D Singleton (no predefined data):

Unity3D Singleton with a Prefab (or a ScriptableObject) used for predefined data:

These are pure-code solutions, DO NOT put anything into any scene, just access it via .Instance

Alternately you could start one up with a [RuntimeInitializeOnLoad] attribute.

There is never a reason to drag a GameObject into a scene if it will be DontDestroyOnLoad.

If you do:

  • you may drag it into something else that isn’t DDOL. FAIL
  • you may drag something else into it that isn’t DDOL. FAIL

Just DO NOT drag anything into a scene that will be marked DontDestroyOnLoad. Just Don’t Do It!

If it isn’t a defective singleton, then it’s just a nullref for you to fix, and that is only done one way:

The answer is always the same… ALWAYS!

How to fix a NullReferenceException error

Three steps to success:

  • Identify what is null ← any other action taken before this step is WASTED TIME
  • Identify why it is null
  • Fix that

NullReference is the single most common error while programming. Fixing it is always the same.

Some notes on how to fix a NullReferenceException error in Unity3D:

http://plbm.com/?p=221

1 Like

A question to ask yourself is… does the EventManager need to be a monobehaviour? Something like that could potentially be a regular or static C# class.

1 Like

Hi,

Thanks all

@Kurt-Dekker that is exactly what I needed

and @spiney199, I’m not overly proud to say that I used a monobehaviour because that’s how a you tube tutorial did it. Now that I stop and think there is no need for it to be one.

The self instantiating singleton class does seem fairly powerful though, especially as my game will (ultimately) continually be navigating between scenes.

As always thanks for you help