Enemy Raycast not working

I am simply trying to have my enemy follow my character with the help of this script i put together. But the enemy won't detect me at all:

//object to be followed
var detectObject: Transform;
var standing = false;
var attackSpeed = 6;
private var characterController : CharacterController;
characterController = GetComponent(CharacterController);
private var nextFire = 0.0;
var fireRate = .5;

var fieldOfViewRange : float; 
var minPlayerDetectDistance : float; 
var rayRange : float; 
private var rayDirection = Vector3.zero;

function Start()
{   
        detectObject = GameObject.FindWithTag("Player").transform;
        animation.wrapMode = WrapMode.Loop;
        animation.Play("idle");
        animation["run"].speed = 1;

}

function Update () 
{

    if (detectObject)
    {
        if(CanSeePlayer())
        {
            //print("attack");
            Debug.Log("SEE YOU");
            animation.CrossFade("run");
            attack();
            return;

        }
        else 
        {
            GetComponent(SmoothLookAt).enabled = false;
            animation.CrossFade("idle");
        }

    }

}

function attack()
{

        var nextFireTime = 0;
        var dist = Vector3.Distance(detectObject.position, transform.position);

    if(dist<5)
    {
        //Debug.Log("HIT");
        animation.CrossFade("attack");
        characterController.SimpleMove(Vector3.forward*0);

        if(Time.time > nextFire)
        {
            nextFire = Time.time + fireRate;
            detectObject.SendMessage("ApplyDamage" , 1);
        }
    }
    else
    {
    direction = transform.TransformDirection(Vector3.forward * attackSpeed);
    characterController.SimpleMove(direction);
    GetComponent(SmoothLookAt).enabled = true;
    //GetComponent(ConstantForce).enabled = true;
    }

}

function CanSeePlayer() : boolean
{
    var hit : RaycastHit;
    rayDirection = detectObject.transform.position - transform.position;
    var distanceToPlayer = Vector3.Distance(transform.position, detectObject.transform.position);

    if(Physics.Raycast (transform.position, rayDirection, hit)){ // If the player is very close behind the enemy and not in view the enemy will detect the player
        if((hit.transform.tag == "Player") && (distanceToPlayer <= minPlayerDetectDistance)){
            Debug.Log("Caught player sneaking up behind!");
            return true;
        }
    }

    if((Vector3.Angle(rayDirection, transform.forward)) < fieldOfViewRange){ // Detect if player is within the field of view
        if (Physics.Raycast (transform.position, rayDirection, hit, rayRange)) {

            if (hit.transform.tag == "Player") {
                Debug.Log("Can see player");
                return true;
            }else{
                Debug.Log("Can not see player");
                return false;
            }
        }
    }
}

function OnDrawGizmosSelected ()
{
    // Draws a line in front of the player and one behind this is used to visually illustrate the detection ranges in front and behind the enemy
    Gizmos.color = Color.magenta; // the color used to detect the player in front
    Gizmos.DrawRay (transform.position, transform.forward * rayRange);
    Gizmos.color = Color.yellow; // the color used to detect the player from behind
    Gizmos.DrawRay (transform.position, transform.forward * -minPlayerDetectDistance);      
}

any ideas please?

That's a lot of code to review. I'll just jump to the main problem and see what can be derived from that information.

But the enemy won't detect me at all.

This leads me to think that `detectObject` is null. There seems to only be one location where this variable is set - during `Start()`.

detectObject = GameObject.FindWithTag("Player").transform;

For this to work, you must ensure three things.

  1. You must have an object with a tag called "Player" in your Scene.
  2. The object must exist and have that tag applied before `Start()` is run.
  3. The object must not be deactivated.

I hope this helps.


Upon further investigation, your raycast may be hitting the object that the ray emerge from. Luckily you can pass a layermask to test collision with only certain masks. See the link about raycasts.

Here is some updated information about how you can cast rays against anything but layer 10. Please note that in case your enemies don't have any colliders this point is moot. It only applies as long there is a chance the ray might be hitting its own collider(s).

// 10.. Or whatever your monster layer is.
var monsterLayer : int = 10; 

// All other layers but the monster layer.
var notMonsterLayerMask : int  = ~(1 << monsterLayer);

if(Physics.Raycast (transform.position, rayDirection, hit, 
                    Mathf.Infinity, notMonsterLayerMask)) 
{ 
    // ...