I’m currently trying to write a piece of code that does something that is theoretically very simple. I have a list of walk points and scientists that I need to test if an alien (the game object where this script is attached) can see. I’m trying to use raycasting to determine this. here’s the code I have so far:
public List<GameObject> test;
public List<GameObject> importantThingsToSee;
public List<GameObject> seeableScientists;
public List<GameObject> seeableWalkPoints;
public void Awake()
{
importantThingsToSee.AddRange(GameObject.FindGameObjectsWithTag("Scientist"));
importantThingsToSee.AddRange(GameObject.FindGameObjectsWithTag("Walk Point"));
PickANewPoint();
}
public void PickANewPoint()
{
seeableScientists.Clear();
seeableWalkPoints.Clear();
foreach (GameObject importantGameObject in importantThingsToSee)
{
Ray ray = new Ray(transform.position, transform.position - importantGameObject.transform.position);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
test.Add(hit.transform.gameObject);
foreach (GameObject compareImportantGameObject in importantThingsToSee)
{
Debug.Log(hit.transform.gameObject + " when compared to " + compareImportantGameObject);
if (GameObject.ReferenceEquals(hit.transform.gameObject, compareImportantGameObject) && compareImportantGameObject.tag == "Scientist")
{
Debug.Log("... is a successful scientist!");
seeableScientists.Add(compareImportantGameObject);
}
else if (GameObject.ReferenceEquals(hit.transform.gameObject, compareImportantGameObject) && compareImportantGameObject.tag == "Walk Point")
{
Debug.Log("... is a successful walk point!");
seeableWalkPoints.Add(compareImportantGameObject);
}
else
{
Debug.Log("... is a faliure.");
}
}
}
}
}
The code should work like this: I have one list of both the walk points and the scientists. When I run the game, that list gets filled correctly. Then it makes a ray and casts it to every gameobject in that list. At this point, I tried to compare the hit to the game object it was referencing at the time, but the raycast was out of sync with the foreach loop by the time that if statement was called. My “solution” was to put another foreach loop inside of the original and test the hit with every single game object in the importantThingsToSee list. In my scene there should be 6 objects it does a raycast for, but it’s only doing 5, and at least 2 of those are going in what appears to be the exact opposite direction of where they’re supposed to be going. Any help would be appreciated, thanks!