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.
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 );
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.)