How to make an enemy raycast work

My aim is to get an object to follow me around, but only when it can see me. I know that it’s an issue with the raycast from what I get output from my Debug.Logs, even when I’m in line of sight of the beast, it outputs “we have a problem” or “Did not hit” and it takes me moving to seemingly random locations to fix that. I have the object emitting the raycast, which I called the beast, on the “Ignore Raycast” layer, just to make sure it wasn’t getting stuck on itself. I have the player on the 9th layer, and my ground and walls on the 8th layer. Any ideas on what might be going wrong?

using System.Collections;
using UnityEngine;
using UnityEngine.AI;

public class TheBeastsMovementScriptThingy : MonoBehaviour
{

    public GameObject Player;
    public GameObject Beast;
    public NavMeshAgent agent;

    void Update()
    {         
    Player = GameObject.Find("fpp");
    Beast = GameObject.Find("beast");

    int layerMask = 1 << 9;
    layerMask = ~layerMask;

    int layerMask2 = 1 << 8;
    layerMask2 = ~layerMask2;

    RaycastHit hit;
        if (Physics.Raycast(transform.position - Player.transform.position, transform.position - Player.transform.position, out hit, Mathf.Infinity, layerMask2))
            {
                Debug.Log("Did Not Hit");
                var myVector = Beast.transform.position;
                agent.SetDestination(myVector);
            }
        else
        {
    if (Physics.Raycast(transform.position - Player.transform.position, transform.position - Player.transform.position, out hit, Mathf.Infinity, layerMask))
    {
        Debug.Log("Did Hit");
        var myVector = Player.transform.position;
        agent.SetDestination(myVector);
    }
        else
        {
                Debug.Log("We Have A Problem");
                var myVector = Beast.transform.position;
                agent.SetDestination(myVector);
            }
        }
}
}

Hi,
Thanks for your post. Have you ever considered placing a cone or a cylinder with the mesh renderer turned off, (attached to the enemy object), with a collider on the cone which fires OnCollisionEnter when it 'touches" the player object and OnCollisionExit when it stops touching the Player object?

Unity - Scripting API: Collider.OnCollisionEnter(Collision) for starters.

Might be a whole lot easier than using Raycasts…

Keep on Creating!

Justin of JustinTime Studio
http://unity3d.expert