Search code examples
c#unity-game-enginecolorsparticle-system

How to set "startColor" of ParticleSystem in Unity 2017 in C#?


I am trying to change the "startColor" field of the ParticleSystem in Unity 2017.

I try to write the code in 2 different ways in C#.

The first way is:

ParticleSystem.MainModule settings =
GetComponent<ParticleSystem>().main;

settings.startColor = new Color(9, 251, 122, 128);

and the second way is:

GetComponent<ParticleSystem>().startColor  =  new Color(9, 251, 122, 128);

But, in both cases, when I run the code, the startColor is automatically set to WHITE, which is (255, 255, 255, 128).

It seems that the code above used to work in older versions of Unity. But, in Unity 2017, it fails to change "startColor" properly.

Please let me know how to fix it. Thanks.

PS:

Here is the FULL original question and answer (with correct C# syntax) inside Unity Forum: https://answers.unity.com/questions/604246/how-to-change-the-color-of-particle-system.html

Please note that it seems that solution may work well for older versions of Unity and does not work with Unity 2017 (unless I am mistaken).


Solution

  • It seems that the code above used to work in older versions of Unity. But, in Unity 2017, it fails to change "startColor" properly.

    I am even surprised that it worked at-all in the previous version. Note that what you have is an undefined behavior.

    Color takes 0 to 1 value and Color32 takes 0 to 255 value range.

    You can still use 0 to 255 range with Color but divide it by 255

    settings.startColor = new Color(9 / 255f, 251 / 255f, 122 / 255f, 128 / 255f);
    

    Or use create Color from Color32

    Color color = new Color32(9, 251, 122, 128);
    settings.startColor = color;