Raycasting to each Gameobject in a list

I have created a list of all anything tagged a player, and in the future will add things to this list, but for the moment I want to be able to raycast to each object within the list so long as there is an object in the list. I’ve been looking around and haven’t found an answer, so I’m here now. Of course, if the player is behind a wall, I shoulnd’t be able to hit them with the raycast. So far, I’m doing it with a single ray in another script, however, if there are multiple objects in its field of view, it has to look at them all instead of one. So, How can I raycast to each gameobject in my list?

public class FieldOfView : MonoBehaviour {

 public List  thingsInFieldofView = new List();
 void Start()
 {
 }
 void Update()
 {
     
 }
 void OnTriggerEnter(Collider other)
 {
     if (other.gameObject.tag == "Player")
     {
         thingsInFieldofView.Add(other.gameObject);
     }
 }
 void OnTriggerExit(Collider other)
 {
     if (other.gameObject.tag == "Player")
     {
         thingsInFieldofView.Remove(other.gameObject);
     }
 }
}

Use a ‘for’ loop to iterate through your list. The code within the for loop will run on each element of the list as it goes through.

  • Make List of gamebjects and assign
    all enimes/objects, whic you want to
    cast ray from player to object.

Attach script to the player

private void Update()
    {
        CheckForHit();
    }
private void CheckForHit()
{
    foreach (var enemie in RaycastObject)
    {
        var ray = new Ray(transform.position, enemie.transform.position);
        RaycastHit hit;

        Debug.DrawRay(transform.position, enemie.transform.position,
            Color.red);

        if (Physics.Raycast(ray, out hit))
        {
        }
    }
}

and iterate through the list and cast ray from player to all objects.