Why doesn't my code seem to change particle color?

Hi, im trying to change the color of the particles but it doesnt seems to work... Please, can you help me and tell me what im doing wrong?? . This is the script that i attached to my particle system:

ParticleAnimator particleAnimator = (ParticleAnimator)GetComponent("PS");
Color[] modifiedColors = particleAnimator.colorAnimation;
modifiedColors[0] = Color.red;
modifiedColors[1] = Color.blue;
modifiedColors[2] = Color.red;
modifiedColors[3] = Color.blue;
modifiedColors[4] = Color.red;
particleAnimator.colorAnimation = modifiedColors;

PS is de name of the particle system. Thanks!!

// The faulty code:
ParticleAnimator particleAnimator = (ParticleAnimator)GetComponent("PS");

In your code, you're trying to get a component using Component.GetComponent that is of the type "PS". This is an error. You must supply the component type, not the gameobject name.

This will result in either:

  • Null reference exception when you try to use it (since there was no component of type PS found).
  • Invalid cast exception (if PS is a type that exist and is placed on the game object).

Try this code instead (I use the generic overload since it seems we're dealing with C#):

var particleAnimator = GetComponent<ParticleAnimator>();

// Same as:
// var particleAnimator = (ParticleAnimator)GetComponent("ParticleAnimator");
// But alot cleaner imo.

If your particle animator is not on the same object as your script (the "PS" object, I reckon), then you can find it using GameObject.Find and access it using GameObject.GetComponent like such:

var ps = GameObject.Find("PS");
var particleAnimator = ps.GetComponent<ParticleAnimator>();

  • Note I used var keyword to shorten my post and make it more readable. This is not required.