raycast hit distance issue

The Distance variable just turn into random numbers when i click the mouse button. What did i do wrong? Please help :slight_smile:

var TheDamage : int = 50;
var Distance : float;
var MaxDistance : float = 1.5;

function Update() {

if (Input.GetMouseButtonDown(0)) {
	var hit : RaycastHit;
	Distance = hit.distance;
	Debug.Log("Pressed left click.");
	if (Physics.Raycast (transform.position, transform.TransformDirection(Vector3.forward), hit)) {
		Distance = hit.distance;
		if (Distance < MaxDistance)
			hit.transform.SendMessage("ApplyDamage", TheDamage, SendMessageOptions.DontRequireReceiver);


This line appears twice:

Distance = hit.distance;

A RaycastHit is only safe to access after it has been used in a raycast call, and even then only if that call returned true (indicating that a hit occurred).

The first Distance = hit.distance; occurs before you’ve actually fired a raycast, which means that you may be reading garbage data.

You should only read from hit if the raycast returns true.