InvalidCastException when trying to access child components

I can’t make the fire start in chapter 8 of “Unity 3.x Game Development Essentials”. During runtime the following error is thrown:

InvalidCastException: Cannot cast from source type to destination type.
Inventory.LightFire (UnityEngine.GameObject campfire) (at Assets/Scripts/Inventory.js:66)
Inventory.OnControllerColliderHit (UnityEngine.ControllerColliderHit col) (at Assets/Scripts/Inventory.js:57)
UnityEngine.CharacterController:Move(Vector3)
CharacterMotor:UpdateFunction() (at Assets/Standard Assets/Character Controllers/Sources/Scripts/CharacterMotor.js:229)
CharacterMotor:FixedUpdate() (at Assets/Standard Assets/Character Controllers/Sources/Scripts/CharacterMotor.js:331)

Here is the relevant code:

function OnControllerColliderHit(col:ControllerColliderHit) {
	if(col.gameObject.name == "campfire") {
		Debug.Log(col.gameObject.GetType());
		if(haveMatches) {
			LightFire(col.gameObject);
		} else {
			textHints.SendMessage("ShowHint", "I could use this campfire to signal for help..

If only i could light it.");
}
}
}

function LightFire(campfire:GameObject) {
	var fireEmitters:ParticleEmitter[];
	fireEmitters = campfire.GetComponentsInChildren(ParticleEmitter); //Exception here
	
	for (var emitter:ParticleEmitter in fireEmitters) {
		emitter.emit = true;
	}
	
	campfire.audio.Play();
	
	Destroy(matchGUI);
	haveMatches = false;
}

Hi there, I cover how to correct this bug in my errata pages for the book, see the workaround there, but Senad is correct in his / her assumption that casting to generic Component solves the issue, see the site for any other mistakes in the book.

http://unitybook.net/book-errata/

Thanks for buying the book, I hope it helps you get started with Unity.

I do not see anything wrong in that code. Maybe you can look at what GetComponentsInChildren() returns in debug mode to get a hint at the problem.

For this purpose you can change the type of fireEmitters to Component to avoid the exception. (and change it back later)