Enemy does not detect player through walls.

I am working on a game where the enemy detects if the player is close to it and then if it is, it follows the player and attacks but the problem Im having is with the enemy detecting the player through walls. it should not know the player is there if there is a wall between them.

player = GameObject.FindGameObjectWithTag("Player");
    detectPlayer = player.transform;
float closeDistance = 8.0f;
if (detectPlayer)
	{
		Vector3 offset = detectPlayer.position - transform.position;
		float sqrLen = offset.sqrMagnitude;
		
		if (sqrLen < closeDistance * closeDistance)
		{
			// turn and shoot the player
		}
	}

I am using this to know if the player is close but i want walls to obstruct the range. Im not sure how to do that.

Hello!
You can use a raycast from the enemy to the player, and detect if that raycast is intersecting a wall.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AnimManager : MonoBehaviour {

    public GameObject player;

    public GameObject enemy;

    // All walls are on this layer
    public int walls;

    void Update()
    {
        // Test if the raycast going from the enemy to the player is not intersecting a wall
        if (!Physics.Raycast(enemy.transform.position, (player.transform.position - enemy.transform.position), walls))
        {
            // If enemy is in range of player, attack player
        }
    }
}

Please ask any questions or clarifications!

Not an expert on this but based experiences with my projects … Have you created a nav map for your scene/level? Do your walls have colliders (not triggers) and a layer set? If your walls move are they set as nav collidable objects? Just suggestions on some things to check :wink: