- Home /
Unity the NullReferenceException wizard
public ParticleSystem mySparkles;
public Color EmitColor;
void Awake()
{
Occupied = false;
mySparkles = gameObject.GetComponent<ParticleSystem>();
EmitColor = new Color( 0.8f, 0f, 0f, 1f); // Sets the color RGBA.
//mySparkles.enableEmission = false;
mySparkles.startColor = EmitColor;
}
Unity claims NullReferenceException, but still applies the red color as wanted?
...how do I rewrite this to make Unity not throwing an error, it seems to ignore.
Not sure. $$anonymous$$aybe when Awake is called the particle system hasn't been loaded? Try moving the code to Start?
Answer by CHPedersen · Feb 18, 2014 at 01:22 PM
I think it's because this script is applied to more than one gameobject, and the other one doesn't have a particle system. So it applies the color correctly for one gameobject and throws an exception for the other.
Answer by flamy · Feb 18, 2014 at 01:43 PM
if(mySparkles != null)
mySparkles.startColor = EmitColor;
if this doesnt give error it means the object mySparkles was empty. or probably you have attached the intended script to other objects too other than the particle system. And this would prove the point that the color is applied regardless of getting null reference.
to check if the script is attached else where go to hierarchy and type t:YourScriptName you should get the list of all objects with the script attached.
I dont see any other error and it is confirmed by you since the error occurred even when the code was moved to start.