Bullet Script Problem

I have my bullet script everything is right but i wanted to add something to make my bullet disapear when it collide with something a wall for exemple here’s the script

 using UnityEngine;
 
 /// <summary>
 /// Projectile behavior
 /// </summary>
 public class ShootScript : MonoBehaviour
 {
     // 1 - Designer variables
 
     /// <summary>
     /// Damage inflicted
     /// </summary>
     public int damage = 2;
 
     /// <summary>
     /// Projectile damage player or enemies?
     /// </summary>
     public bool isEnemyShot = false;
 
     void Start()
     {
         // 2 - Limited time to live to avoid any leak
         Destroy (gameObject, 1);
     }// 20sec
         
 }

i wanted to add something like this

private void OnCollisionEnter(Collision collision)
         {
             
             if ( collision.gameObject.name == "wall" )
             {
                 Destroy(collision.gameObject);
             }
         }

Just add the OnCollisionEnter code to this script in order to kill the bullet whenever it collides with anything:

      void OnCollisionEnter (Collision collision) {
              // if bullet collided with anything...
              Destroy (gameObject); // it suicides
      }

Setup:

  • Put collider triggers on the objects you want the projectile to hit.

  • Put a collider and ridgidbody on your projectile

  • Add below script to projectile.

     void OnTriggerEnter(Collider col)
          {
          if(col.gameObject.tag == "Enemy")
          {
            // call enemy take damage method and pass projectile damage 
            col.gameObject.GetComponent<enemy>().TakeDamage(projectileDamage);
            Destroy(gameObject);
          }
          if(col.gameObject.tag == "wall")
          {
            Destroy(gameObject);
          }
     }
    

Getting the gameObject.tag works better here because you may have multiple enemies. You would want to name them differently. However they are all enemies, so just add a tag to whatever object is an “enemy”.

You can also fire off multiple projectiles all with different damage amounts, then call the “TakeDamage” function on the corresponding objects it hits.