- Home /
Trouble destroying a instantiated Prefab?
Hey, so I have a game where two players battle each other by colliding. After each collision their health decreases a little and when it hits 0 then they will be destroyed. So the way I have it set up is my game manager script instantiates both players from a set of prefabs from the void start () function. Then the gamemanager also keeps track of health and when health = 0 destroys the player. I use a separate script on a child object in each player object that determines when to activate the function damage () which does the heavy lifting in the gamemanager script. So basically the player calls to the manager each time its hit.
The problem is that even though I have spent the last 5 hours researching it, the instantiated prefab wont be destroyed - the function its in is calling itself but its just not being destroyed. Im wondering if this is a more complex issue involving calling a public void function from another script thats also custom or maybe its a issue with instantiating objects from the start () function.
void Start () {
PlayerOne = (GameObject) Instantiate (Player1, Player1Spwn.transform.position, Quaternion.identity);
PlayerTwo = (GameObject) Instantiate (Player2, Player2Spwn.transform.position, Quaternion.identity);
}
void Update () {
if (Input.GetKeyDown (KeyCode.G)) {
Debug.Log (health1);
}
}
public void DamageP1 () {
health1 = health1 - 10;
Debug.Log (health1);
if (health1 <= 0) {
Destroy (PlayerOne);
Debug.Log ("hey");
}
}
public void DamageP2 () {
health2 = health2 - 10;
Debug.Log (health2);
if (health2 <= 0) {
Destroy (PlayerTwo);
Debug.Log ("hey");
}
}
}
Here is the call function thing in the child object:
void OnTriggerEnter2D (Collider2D theOtherCollider) {
if (theOtherCollider.gameObject.tag == "Player2") {
script.DamageP2 ();
}
Thanks in advance!!!
Please post the entire script when asking for help - or at least all the relevant parts. (You're missing where your variables are declared, your class names, and where the "child object" gets access to "script") If you edit it to provide more info, I might be able to help.
Instantiating from Start is fine. Calling public functions on other objects is fine.
On a side note, your code design could probably use some work. Why do the "children" not manage their own health? Think in terms of OOP. What is the purpose of each class, what should it handle?
Also, you have some outputs in your code. $$anonymous$$nowing how these behave would also help narrow down the issue. In particular if you are outputting health1||health2 upon collision.
Answer by heyhujiao · Dec 13, 2015 at 06:31 AM
Well, you can try this -
void OnTriggerEnter2D (Collider2D theOtherCollider) {
if (theOtherCollider.gameObject.tag == "Player2") {
script.DamageP2 ();
if (gameObject.name == "Player2(Clone)")
{
Destroy(gameObject);
}
}