InvalidCastException

Hello!
When I find the child component by GetComponentsInChildren() method, I’ve got InvalidCastException. here is my coding.

var fireEmitters = campfire.GetComponentsInChildren(ParticleEmitter);
	for(var emitter : ParticleEmitter in fireEmitters){
		emitter.emit = true;
	}

There are two Particle System objects in the campfire. But I have got null.

Thanks.

Try:

var fireEmitters : ParticleEmitter = campfire.GetComponentsInChildren(ParticleEmitter);

or

var fireEmitters : ParticleEmitter = campfire.GetComponentsInChildren(ParticleEmitter) as ParticleEmitter;

or

var fireEmitters : ParticleEmitter
fireEmitters = campfire.GetComponentsInChildren(ParticleEmitter);

or

var fireEmitters : ParticleEmitter = campfire.GetComponentInChildren.();

Yes. I did. But I still got InvalidCastException. I found one thing. GetComponentsInChildren method returns Component array. so I have change the coding.

var fireEmitters : Component[] = campfire.GetComponentsInChildren(ParticleEmitter);
for(var emitter : Component in fireEmitters){
	emitter.particleEmitter.emit = true;
}

Now I got the two Particle emitter according to this coding.

Thanks a lot.

This is how I got it working on my own script:

var laserControllers: Component[];
laserControllers = GetComponentsInChildren(LaserController);
for(var laserController: Component in laserControllers) {
    var laserControllerScript: LaserController = laserController;
    laserControllerScript.Fire();
}

It seems like the array has to be of type Component but the items can be cast to your own type inside the for loop.