Unityscript - Using "as" to cast for GetComponentsInChildren returns empty array

I have an instantiated GameObject with multiple ParticleSystems on it (each on a GameObject that is a child of the main GameObject). To stop the entire thing from emitting further particles, I use this:

function StopEmission(theParticleObject : GameObject) {
   	var tempComponents : Component[];
	tempComponents = theParticleObject.GetComponentsInChildren(ParticleSystem);
	for (var particle : ParticleSystem in tempComponents) {
		particle.enableEmission = false;
	}
}

However this generates an “implicit downcast” warning. I understand I should be able to cast out the error as follows:

	var tempComponents : ParticleSystem[] = theParticleObject.GetComponentsInChildren(ParticleSystem) as ParticleSystem[];
	for (var particle : ParticleSystem in tempComponents) {
		particle.enableEmission = false;
	}

However, the for loop in this case never returns any results and I’m not sure why. I believe “as” will return null when the casting fails, but why shouldn’t this work?

EDIT: This doesn’t work either, harrumph:

	var tempComponents : Component[];
	tempComponents = theParticleObject.GetComponentsInChildren(ParticleSystem);
	for (var particle : ParticleSystem in tempComponents as ParticleSystem) {
		particle.enableEmission = false;
	}

Downcasting isn't a problem, it's just a warning that you might not have intended it.

Aah, thankyou, that is great information. I was holding my breath after your answer, wondering if and what I got wrong.

Well, also don't use strings if you can avoid it. ;)

Oh, and you would want to type as ParticleSystem[] rather than ParticleSystem (or rather, you would if that worked); it's an array, so trying to cast an array as a not-array would result in an error. Also, the casting doesn't really have anything to do with strings; GetComponentsInChildren() always returns Component[] regardless. So the casting doesn't work for whatever reason. That's why it's better to use GetComponentsInChildren.< Type >(), since that does cast as an array of the correct type.

That makes sense, because the command is GetComponents so it does indeed return an array. Way out of my depth here, shall remember generic declaration now I've seen it. Thanks.

1 Answer

1

Use the generic version of GetComponentsInChildren; that way the array is automatically cast to ParticleSystem:

function StopEmission (theParticleObject : GameObject) {
    var tempComponents = theParticleObject.GetComponentsInChildren.<ParticleSystem>();
    for (var particle in tempComponents) {
       particle.enableEmission = false;
    }
}

Bingo! That did it; thanks Eric. Why does GetComponentsInChildren(ParticleSystem) exist if only GetComponentsInChildren.ParticleSystem>(); works "properly?"

GetComponentsInChildren.< Type >() was added later. The non-generic version does work properly, just not conveniently. ;) (I rarely ever want to deal with Component.)