user5641102
user5641102

Reputation: 37

How to destroy the whole prefab when the game object collides with the main character?

What I'm trying to do is to make my monster disappear when my main char collides with it. So, I attached this script to my monster, but I can't get it to work. I succeeded in destroying monster's RigidBody component but I can't seem to destroy the whole thing.

using UnityEngine;
using System.Collections;

public class Dying: MonoBehaviour {
private Rigidbody rbody;
public GameObject prefab;


void Start () {
    rbody = GetComponent<Rigidbody>();
GameObject obj = Instantiate(prefab);

}


void Update () {


} 
void OnCollisionEnter(Collision col)
{ 
    print(col.collider.name);
    if(col.collider.name =="unitychan")
    {
         Destroy(prefab.gameObject);

    }
 }
}

Upvotes: 1

Views: 79

Answers (1)

AustinWBryan
AustinWBryan

Reputation: 3326

What might be the problem is that you are trying to destroy either the object running the script, or some other random object. You typically never destroy the object running the script. Also, col contains the object that was collided with. so you can just do this:

void OnCollisionEnter(Collision col)
{
    if (!col.collider.name == "unitychan") return;

    Destroy(col.gameObject);
}

Upvotes: 2

Related Questions