- Home /
Destroy game object with tag
Hi so I am trying to get my player to be able to pick up health items with the following code:
var maxHealth = 100;
public static var currentHealth = 100;
var PlayerHealthDisplay : GUIText;
var meep;
function Start() {
DisplayAmount();
}
function DisplayAmount () {
PlayerHealthDisplay.text = ""+ currentHealth;
}
function OnTriggerEnter(collider:Collider) {
meep = gameObject.FindGameObjectsWithTag ("meep");
if (collider.tag == "beep"){
currentHealth += -10;
PlayerHealthDisplay.text = ""+ currentHealth;
}
else if (collider.tag == "meep"){
currentHealth += 5;
PlayerHealthDisplay.text = ""+ currentHealth;
Destroy(meep);
}
}
The health points on objects tagged with "meep" are added but the specific health object I run over is not destroyed. When I run over the object, I get the error:
InvalidCastException: Cannot cast from source type to destination type. health.OnTriggerEnter (UnityEngine.Collider collider) (at Assets/health.js:22)
I would like to be able to run over an object, destroy only this health object, not the others, and receive health points. Thanks!
Answer by brentatplayful · Nov 04, 2014 at 05:54 PM
Do use gameObject.FindGameObjectsWithTag of this. I'm guessing it's the destroy call causing the invalid cast. use should use collider.gameObject.
try this: get rid of the meet variable and replace Destroy(meep); with Destroy(collider.gameObject);