- Home /
Accessing and changing particle color in script
I have a script attached to a particle, "Sparkle Rising" from the Particle Package to be exact. This script is supposed to make the particles fade away over time. I try to achieve it like this:
Color colorStart = new Color(0.2f, 1.0f, 0.2f, 1.0f);
Color colorEnd = new Color(0.2f, 1.0f, 0.2f, 0.0f);
bool fade = false; // can be set to true
void Update () {
if(fade) {
ParticleAnimator[] animators = gameObject.GetComponentsInChildren<ParticleAnimator>();
foreach(ParticleAnimator animator in animators) {
for(int i=0; i<animator.colorAnimation.Length; i++) {
animator.colorAnimation[i] = Color.Lerp(colorStart, colorEnd, lifeTime/initialLifeTime);
}
}
lifeTime -= Time.deltaTime;
if(lifeTime < 0)
Destroy(gameObject);
}
}
The problem is the call to get the ParticleAnimator for the children I think. It should be right, but it does nothing. "Sparkle Rising" is a particle with two children, sparkleParticles and sparkleParticlesSecondary, which both have a ParticleAnimator, and changing their content with the editor works just fine. But changing it from the script doesnt't do anything, and I don't know why. And I know that everything should get executed, because Destroy(gameObject) gets called.
Answer by ArniBoy · Aug 10, 2013 at 09:19 AM
I have found the solution, should have occurred to me sooner to check the documentation for ParticleAnimator.ColorAnimation. In there, I found these lines:
Description: Colors the particles will cycle through over their lifetime. Currently you cannot directly modify a single index of this array. Instead, you need to grab the entire array, modify it, and assign it back to the Particle Animator.
Which means, that much like changing the transform of a gameObject, the access has to look like this:
foreach(ParticleAnimator animator in animators) {
Color[] newColors = animator.colorAnimation;
for(int i=0; i<newColors.Length; i++) {
newColors[i] = Color.Lerp(colorStart, colorEnd, lifeTime/initialLifeTime);
}
animator.colorAnimation = newColors;
}
It works fine now.