- Home /
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.
Answer by DaveA · Mar 28, 2012 at 02:40 AM
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.();
Answer by kyawswaaung · Mar 28, 2012 at 04:11 AM
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.
Answer by flodis · Feb 26, 2013 at 03:40 AM
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.
Your answer
Follow this Question
Related Questions
Invalid Cast Exception 1 Answer
I can't see a reason for this Array.Reverse() error 3 Answers
Invalid Cast Exception 1 Answer
InvalidCastException: Specified cast is not valid. (NETWORKING) 1 Answer