Invalid Cast Exception Error (on instantiation)


When I try to do the following in my PlayerInstantiatedParticles C# file:

ParticleAnimator [] myEmissions;
// under certain condtions for the player instantiate the particles
myEmissions = (ParticleAnimator) Instantiate(ParticlePrefab, 
    transform.position, Quaternion.identity);

I get a run-time invalid cast exception error: Cannot cast from source type to destination type.

--This error leads me to believe that the FadeAndClearParticles function is not working. I believe that it would work if I could mitigate the invalid cast exception error..

(The instantiation works fine, I just can't see any change with the particles fading)

I could use a GameObject to prevent the invalid cast exception error, but I need to be able to access the colorAnimation member for fading particles out and then clearing them:

//after instantiation
public static Color [] holder;

public static ParticleEmitter [] myEmitters;

public static IEnumerator FadeAndClearParticles()
    holder = new Color[5];
    holder[0].a = 1;

    while (holder[0].a > 0) {
        ParticleAnimator [] myEmits = new ParticleAnimator [] 
            { PlayerInstantiatedParticles.myEmissions };

        foreach (ParticleAnimator m_emitter in myEmits) {
            if (m_emitter) {                
                holder = m_emitter.colorAnimation;
                holder[0].a -= 0.005f;
                m_emitter.colorAnimation = holder;
    foreach (ParticleAnimator m_emitter in emitters) {
        if (m_emitter) {
            m_emitter.particleEmitter.emit = false;

    yield return 0;

Might I ask why you even have a function called "FadeAndClearParticles", when the particle animator can do that for you, without having to write any code? I may be wrong, but it looks like you're trying to reinvent the wheel here... just set one of the five color properties in the ParticleAnimator component on your game object (including the Alpha value if you're using a transparent particle shader), and then your particles will animate through each color automatically. The particles are also automatically cleaned up once they die. So instead of using this script, you could just set the five color properties on the ParticleAnimator to slowly fade out over time, something like this:

alt text

Notice the alpha values slowly fade out over time, going from 255 -> 0. This will do exactly what your script is trying to do (except it does it better).

You need to be using a Transparent shader for this to work, though. Unity comes with some good Transparent particle shaders.