how to make enemy raycast follow player

basically i want it so that a enemy has a ray cast that follows the player but if the player of behind a wall the ray cast will still follow the player but the ray cast wont go through a wall

When you say raycast, do you mean a visible line? Physics raycasts will automatically be stopped by anything in it’s path as long as the obstacle is in the raycast’s layers. Assuming you want a visible line, I recommend using a line renderer.

private LineRenderer lr; //Make sure you attach a line renderer to your enemy
public Transform player;
public LayerMask obstacleLayers;

void Start(){
    lr = GetComponent<LineRenderer>();
    lr.positionCount = 2;

void Update(){

    RaycastHit rayHit = new RaycastHit();
    Ray ray = new Ray(transform.position, player.position - transform.position);
    lr.SetPosition(0, transform.position);

    if(Physics.Raycast(ray, out rayHit, 1000, obstacleLayers)){
        lr.SetPosition(1, rayHit.point);
    } else{
        lr.SetPosition(1, player.position);


If you are making a 2D game make sure you use Physics2D.Raycast instead