- Home /
Passing particle system in script, getting null reference exception error.
Ok, so my general goal is to activate and de-activate certain particle systems that correspond to spell effects when the player pushes certain buttons. The structure is that each spell has a set of children who each contain a particle system corresponding to the desired effect. To make my code look nicer, I created a class called "SpellStats.cs", and it looks like this:
"public class SpellStats {
private ParticleSystem normalModePS;
private ParticleSystem hGPS;
private ParticleSystem cTPS;"
..... }" (with the appropriate get/set functions)
The 3 particle systems correspond to the 3 possible states of each spell. Now, each spell has attached to it a script which creates a variable of type "SpellStats" and fills in the appropriate values and I intend it to pass this object to another script (called "Spell.cs"). One example of these is as follows:
public class FireballManager : MonoBehaviour
{
private SpellStats stats;
public ParticleSystem normalMode;
public ParticleSystem handGrip;
public ParticleSystem chargedTrigger;
`` private void Awake() {
stats.NormalModePS = normalMode;
stats.HGPS = handGrip;
stats.CTPS = chargedTrigger;
gameObject.GetComponent<Spell>().SpellStat = stats;}
....}
You can see in here that there are three public particle system variables created. I link up the appropriate particle systems to this script in the unity gui. So these 3 public variables are referring to something. However, unity is telling me that the statement "stats.NormalModePS = normalMode;" is causing a null reference exception. I assume this means that the left hand side of the equation is a null reference. Can someone explain how I fix this issue? Is it possible to do what I am trying to do?
Thanks in advance for taking the time to help!
Answer by hexagonius · Dec 08, 2018 at 07:58 PM
you're right, it's null. unlike serializable fields (SerializedFieldAttribute or public), regular fields are initialized the C# default way. In case of reference types to null. this is how to initialize it:
private SpellStats stats = new SpellStats();