how to use raycasting for enemy sight (C#)?

The issue im having is that my enemy can see through walls. Ive been trying to do this for hours and cant quite get it working. Ive seen several other posts about raycasting, but alot of them are outdated or using javascript. Ive tried just regular raycasting to see if it can hit the player, but it results with the enemy seeing him through the walls. I also tried making an array of all the objects that are hit and then checking to see if the player is closer than the others, but this seemed to make the enemy glitch out to See the player and not see the player every frame. Does anybody know how to do this?

as of right now this is what i have

RaycastHit[] hits;
			hits = Physics.RaycastAll (transform.position + Vector3.up * 1.5f, transform.forward, sightDistance);
		for (int i = 0; i < hits.Length; i++) {
			if (hits *.collider.gameObject.Equals (player)) {*
  •  		Debug.Log ("I C YOU");*
    
  •  		animator.SetBool ("isAlert", true);*
    
  •  		playerDistance = Vector3.Distance (transform.position, player.transform.position);*
    
  •  	} else {*
    

_ otherDistance = Vector3.Distance (transform.position, hits .transform.position);_
* }*
* }*
* if (otherDistance < playerDistance)*
* {*
* animator.SetBool (“isAlert”, false);*
* Debug.Log (“NOPE”);*
* }*
* }*
* }*
This is the closest i can get to making it work. the enemy sees the player and starts shooting, then immediately stops seeing the player even when hes right in front of him. i need him to see the player when hes in the line of sight, and need him to stop seeing th eplayer if he moves behind a wall

Use Raycast instead of Raycast all. Raycast all goes through everything. and returns everything that is hit. You are iterating through everything that was hit to see if the player is in there and he always will be provided he is within sightDistance. .Make sure obstacles also have colliders.

Watch the whole video

I think your problem comes from RaycastAll returning arrays that are not in order. you should use something like System.Array.Sort(hits, (x, y) => x.distance.CompareTo(y.distance)); to order your RaycastAll array and then check if the first Hit is on the player.