Making my gun shots do damage [Fast help please]

So i have made a code which should make my gameObject which is a “shotgun” fire bullets when i left click.
But when i left click it fires but it doesn´t do any damage to my enemy and the bullets doesn´t dissapear after the 2 seconds i marked.

Please look at this code and tell me what you think i am doing wrong…

#pragma strict

 

var par : Transform;

var TheDamage = 100;

var theBullet : Rigidbody;

var Speed = 20;

 

private var lineTransform : Vector3;

private var startTransform : Vector3;

 

function Start ()

{

    lineTransform = transform.position;

    startTransform = transform.position;

}

 

function Update (){

 

var hit: RaycastHit;

var ray : Ray = Camera.main.ScreenPointToRay(Vector3(Screen.width*0.5, Screen.height*0.5,0));

 

    if (Input.GetMouseButtonDown(0)) {

        {

            var clone = Instantiate(theBullet, transform.position, transform.rotation);

            clone.velocity = transform.TransformDirection(Vector3(0, 0, Speed));

            hit.transform.SendMessage("ApplyDamage", TheDamage);

            Destroy(clone.gameObject, 2);

            

            lineTransform = hit.point;

        }

    }

}
  1. You never assign anything to hit, so there is nothing to damage.

There is a bigger problem though. You’re mixing two different styles of bullet.

  1. The raycast hit (like counter strike). I forget the technical name for this type, but there is no bullet, there is just an imaginary line (raycast) drawn in the aim direction, whatever object is hit by the raycast is what receives the damage.

  2. The physical bullet (like battlefield). This is the standard bullet type used in most modern games, as it uses physics to make the hit. This is what youve used by calling instantiate, and putting a velocity into the bullet.

The way you need to handle the damage is via collisions.

I suggest you go read up about unity physics. https://docs.unity3d.com/Documentation/Manual/Physics.html

JamesLeeNZ is it possible that you could help me a little with making the code for the Physical bullet (like in battlefield)?

I´m a little stuck here since i´m a bit new to coding and unity3D.

You’ve already done it assuming your bullet is setup correctly.

(it should have a collider and rigidbody, it should use gravity, and should have 0 drag).

All you need to do is make sure there is a collider and rigidbody on the object you want to hit. Once youve done that, you have to add a script with an OnCollisionEnter function. Look at scripting section for more guidance.

If you read the physic docs I linked, it should make more sense.