Unity change the color over life times gradient in particle system in runtime;

I’m working on a game that needs to control ParticleSystem in runtime.
But the problem is that I can’t change the ParticleSystem / ColorOverLifetime / Gradient in runtime and with scripts. Here is my code to do that which didn’t worked :

    ParticleSystem.ColorOverLifetimeModule col = backgroundParticleSystem.colorOverLifetime;

    Gradient gradient = new Gradient();
    GradientColorKey[] colorKeys = new GradientColorKey[2];
    GradientAlphaKey[] alphaKeys = new GradientAlphaKey[1];

    colorKeys[0].color = backgroundParticleStartColor;
    colorKeys[0].time = 0f;

    colorKeys[1].color = backgroundColor;
    colorKeys[1].time = 1f;

    alphaKeys[0].alpha = 1f;
    alphaKeys[0].time = 0f;

    gradient.SetKeys(colorKeys, alphaKeys);

    ParticleSystem.MinMaxGradient gr = col.color;
    gr.gradient = gradient;

In this code I just tried to change the gradient by remaking a new one each time and resetting its ColorKeys and AlphaKeys .

I’m sure that the gradient is setted correctly but somehow the particle system isn’t updating.

>Solution :

I think your last two lines are the issue. Shouldn’t it be

col.color = gradient;

instead like in the doc?

Leave a Reply