Null Reference Errors when placing a tower into the Scene

Hi there,
As soon as I place a tower the output window gets spammed with

NullReferenceException: Do not create your own module instances, get them from a ParticleSystem Instance.

My Ballista prefab has the particle system we created in the correct serializeField
And this is the code for the Attack method.


Ballista

Many thanks for your help

Instead of explicitly specifying ParticleSystem.EmissionModule as the type, use var. All the Unity documentation shows this because projectileParticles.emission is an interface and you are ‘creating’ a concrete type reference which is what the compiler is complaining about. I think. At least that’s what I think

Hey Bixarrio
Ok I must of missed that I did take a look at the documentation just to see what the fully qualified type name would be… I will try with var and let you know.

Thxs

How did this go?

The docs don’t explicitly say ‘use var’. I just saw that the code samples used var.

Emission Module ‘enable’ documentation

The code sample shows

void Update()
{
    var emission = ps.emission; // 'var' here. other docs do the same
    emission.enabled = moduleEnabled;
}

I remembered that the EmissionModule is a struct and when you get a reference to it, you actually get a copy that needs to be given back. Usually

var emission = particles.emission;
emission.enabled = true;
particles.emission = emission;

but even Unity’s documentation didn’t do this, so I was intrigued. Did some more digging. That’s when I saw they said that the module is an interface and does not need to be passed back

Emission Module documentation

So, I just figured the var is what makes their code work over yours because it’s pretty much the only difference between the two. Not entirely sure, but I think when you define it explicitly the compiler calls the constructor of the type in order to cast the interface to the type and this is what triggers the error you got

Privacy & Terms