Changing the colour of particles within code in Unity.

I have tried so many things and nothing is working. The error I receive is ```
NullReferenceException: Do not create your own module instances, get them from a ParticleSystem instance
UnityEngine.ParticleSystem+MainModule.set_startColor (UnityEngine.ParticleSystem+MinMaxGradient value) (at :0)


```csharp
// Text colour is configured through the editor.
public Color textColor;
public GameObject burst;
public ParticleSystem ps;
private Vector2 newLocation;

    private void EmitParticles()
    {
        var ma = ps.main;
        newLocation = m_textComponent.gameObject.transform.GetChild(0).transform.position;
        ma.startColor = new ParticleSystem.MinMaxGradient(textColor, Color.black);
        Instantiate(ps, newLocation, transform.rotation);
    }

Don’t make a new gradient in line 11.

Instead manipulate the one you got back in ma.

This may involve copying it out to a local MinMaxGradient variable, making the changes, then assigning it back

ALSO: the code above is likely changing the stored prefab, assuming that is what is dragged into line 4.

Instead, keep the reference that Instantiate() returns and use that to get the main module of your new copy and to make changes to it.

1 Like

That worked FIRST TRY!! You, sir, are a legend.

1 Like