Search code examples
unity-game-enginecollisiondestroy

How to destroy an initiated GameObject on collision?


I have created a script that spawns bullets/projectiles that moves forward with a certain force. However, the bullet itself does not disappear on collision. Since it is a instantiated object, how do I make it disappear? I've tried OnCollisionEnter() but to no avail. The code below is how i created the bullet.

// Instantiate bullet/projectile
GameObject currentBullet = Instantiate(bullet, attackPoint.position, Quaternion.identity);
        
// Rotate bullet to shoot direction
currentBullet.transform.forward = directionWithSpread.normalized;

// Add forces to bullet
currentBullet.GetComponent<Rigidbody>().AddForce(directionWithSpread.normalized * shootForce, ForceMode.Impulse);
currentBullet.GetComponent<Rigidbody>().AddForce(fpsCam.transform.up * upwardForce, ForceMode.Impulse);

EDIT Perhaps, is there anyway to assign a script to a prefab that will be instantiated?


Solution

  • You can choose two paths to achieve this

    1) Adding the script to the prefab (done in the editor)

    You can edit the prefab (opening it from the editor) and add the script to it.

    2) Adding the script to the instance (done programmatically)

    In this case your first instantiate the prefab and then programmatically add the script to it with something like this:

    GameObject currentBullet = Instantiate(bullet, attackPoint.position, Quaternion.identity);
    
    currentBullet.AddComponent<YourScript>();
    

    3? Using RayCasting (this option in my opinion fits your needs)

    Usually the best way to handle bullets is using RayCast

    In this case the bullet does not need the code to handle its collision but it is just the visual representation of the bullet, the real collision detection and other actions linked to it are controlled by the raycasting, in this way you save some memory

    Hope this helps