Raycast is being unreliable

Hi there,

I have a script that i use to Raycast to an object then send a message to it to execute a function. It works, the problem being that it is very unreliable and seems to act on a kind of delay.

For example, i will approach my enemy, looking directly at him and it is only when I go around to the back of his model and stare at it that the Raycast hits him, sends the message and then executes the desired function. Here is both the Raycast script and the script attached to the enemy.

 var hit : RaycastHit;
    var TheDammage : int = 100;
 
     
    function Update()
    {
    if ( Physics.Raycast( transform.position, transform.forward, hit, 3 ))
    {
    Debug.Log( "ray hit (tag) : " + hit.collider.gameObject.tag + " : " );
     
    if ( hit.collider.gameObject.tag == "EnemyStatic" )
    {
    Debug.Log("HitStaticEnemy");
    hit.transform.SendMessage("ApplyDammage", TheDammage, SendMessageOptions.DontRequireReceiver);
    }
    }
    }

#pragma strict

@script RequireComponent(AudioSource)

var Soundplayed1 = false;
var HorrorHit1: AudioSource;
var Health = 100;

function ApplyDammage (TheDammage : int)
{
	Health -= TheDammage;
	
	if(Health <= 0)
	if(Soundplayed1 == false)
	{
		Dead();
	}
}

function Dead()
{
    GetComponentInChildren(MeshRenderer).enabled = false;
    Debug.Log("MeshHit");
    audio.volume = 1.0;
	HorrorHit1.Play();
	Soundplayed1 = true;
	Destroy (gameObject, 5);
}

Try this:

// [...]

function GetHierarchyName(obj : Transform) : String
{
    if (obj == null)
        return "ROOT";
    return GetHierarchyName(obj.parent) + "/" + obj.name;
}

function Update()
{
    if ( Physics.Raycast( transform.position, transform.forward, hit, 50 ))
    {
        Debug.Log("We hit: " + GetHierarchyName(hit.collider.transform));
        Debug.DrawLine(transform.position, hit.point, Color.yellow, 0.5);
    }
}

this will print the full path in the hierarchy of the object your ray hit. There will also be a line from your ray starting point to the actual hit point. This line will last half a second just to see where the ray actually hits.

ps: you should undock either the scene or game view or dock them next to each other so you can see both at the same time. It’s important that you move the scene view camera to a spot where you have a good view of what happens.

There’s not much we can do about your problems since we can be sure that the raycast works perfectly and without any delay.

pps: Is it possible that the variable “TheDammage” has a different value in the inspector? The inspector holds the actual value so it doesn’t need to be 100 as you might expect.