Do Something When a Object is hit by a raycast

So i simply want to run some code when my character’s Gun Raycast hits a object. That is all i want to do. But nothing is working for me. It would be great if someone helped :).

Try this:

float range = 10f;

void Update ()
{
     if(Input.GetButtonDown("Fire1"))
     {
          RaycastHit hit;
          Ray ray = new Ray(transform.position, transform.forward);

          if(Physics.Raycast(ray, out hit, range))
          {
               if(hit.collider.tag == "Enemy")
               {
                    Debug.Log("Hit!");
               }
          }
     }

     Debug.DrawLine(transform.position, transform.forward * range);
}

What this should do is whenever you click the left mouse button, a raycast should fire and hit an object. If it hits an object with a specific tag, it will log to your console “Hit!”. You can always remove that if statement if you want to see if an object hits anything at all. Then on your game view, you’ll see a button labeled “Gizmos”. Click that and now when you fire your gun, you will be able to see your Raycast live in your scene.