- Home /
How do you destroy only one prefab gameObject?
How would I set it up so when a bullet hits an npc it makes just that one npc disapear. Right now when I shoot an npc it destroys every single prefab on the screen and can't figure out why. Should I have the code to destroy the npc as a component to the npc or the bullet?
If you post your code we could tell you exactly why that's happening.
This is the script attached to the npc
void Update () {
bool npcHit = BulletScript.npcHit;
if (npcHit == true){
Destroy(gameObject);
npcHit = false;
}
This is the script attached to the bullet
void Update () {
if(Physics.Raycast(transform.position, transform.up, out hit, range)){
if(hit.transform.tag == "enemy"){
Destroy(gameObject);
npcHit = true;
}
I usually use OnTriggerEnter or OnCollisionEnter for rigidbodies. The answer given below works. If you need help coding it I'll gladly write it for you as its not large code.
Answer by tw1st3d · Aug 07, 2013 at 02:52 PM
using System.Collections;
using UnityEngine;
class NPCAI : MonoBehavior
{
public void OnCollisionEnter(Collision e)
{
Destroy(e);
}
}
You could set up a simple collision detection like this, that tells it to only destroy the particular object it's colliding with. Just add some logic to determine whether or not it's colliding with a bullet.
Your answer
Follow this Question
Related Questions
i need to destroy prefab clones 1 Answer
Instantiated object is destroyed in scene, but still logs as existing in console. 1 Answer
Destroy and Spawn an Enemy 1 Answer
How to spawn a 'boss' after all enemies defeated and then kill that 'boss'? 1 Answer
Clone of rigid body prefab destruction if at certain position 3 Answers