[SOLVED] InvalidCastException

Hello mates.
I get an error with this code and I can’t understand why.
I instantiate a GUITexture when the player runs out of rockets, as a feedback. No problems.
When I try to instantiate a GUITexture (with a similar code) when the player gets an item, the error happends.
Any help welcome!

var healthFeedbackGUI: GUITexture;

function OnCollisionEnter(collision : Collision) {
if (collision.gameObject.tag == "ihealth")	{
			playerHealth += 40 ;
			
			
		var feedback : GameObject = Instantiate( healthFeedbackGUI );
Destroy(feedback, 1);
}
}

the error:

InvalidCastException: Cannot cast from source type to destination type.

Instantiate returns an Object, not GameObject, so you have to cast it to a GameObject.

var feedback : GameObject = (GameObject)Instantiate( healthFeedbackGUI );

Javascript doesn’t work like that, so that won’t compile. The original code is fine and casts correctly, but the problem is that the "healthFeedbackGUI " variable is of type GUITexture, but you are trying to instantiate it as type GameObject. Both types must be the same. You could also leave healthFeedbackGUI as a GUITexture and do:

var feedback : GameObject = Instantiate( healthFeedbackGUI.gameObject );

–Eric

Ah ok. I don’t use JavaScript. I know that normal JS doesn’t have type casting, but I imagined that Unity’s incarnation might due to it using .NET.

Indeed it does…normally type inferencing takes care of that (like you can do with C# in .net 3.0). Otherwise, specifying the type with “var feedback : GameObject” is sufficient. Actually, technically this would also compile and run without error messages:

var feedback : GameObject = Instantiate( healthFeedbackGUI) as GameObject;

but it wouldn’t do what you want, as long as healthFeedbackGUI is a GUITexture. (As in, the Destroy(feedback, 1); line wouldn’t have any visible effect.)

–Eric

Working! thank you Eric.
I understand why it is working now.
Can you tell me as well why I declare the GUI as a “gameObject” and not as a “GameObject”

btw, am I “declaring” with that?

GameObject is a type, gameObject is a variable.

–Eric