Making Script References Global

I made the typical schoolboy error of trying to use default references on a script, and then attaching that script at runtime, and I’ve spent the last 2 hours chasing null reference exceptions…

So here’s my new plan, I have a class that contains some public static variables, which I’ll use to store some globals. I then have a script attached to a GameObject on the hierarchy which has the script references set up properly through the editor. In the Start function of this script it passes these to the class containing the globals. Here is roughly what I’ve got:

// Common.cs
public static ParticleEmitter emitter;

// Init.cs
public ParticleEmitter particleEmitter;

public void Start()
{
   Common.emitter = particleEmitter;
}

// Test.cs (the script that is dynamically attached)
public void Start()
{
   print( Common.emitter );
   Instantiate( Common.emitter );
}

The print command prints out UnityEngine.ParticleEmitter in the log, but the call to Instantiate still says the prefab is null… What am I missing here?

Cheers
Spec

This looks like a matter of which object is initialised first. Generally, there’s no way to guarantee the order in which objects will have their Start functions called. However, if you set up the static ParticleEmitter variable from the Awake method of Init.cs, it will be ready before any Start method is called.