[fixed] How can I return a List positions of objects with a specific component?

SOLUTION: I was using a 2dBoxCollider. When I used a sphere collider on my object the code started working.

For an AI script, I am trying to have the script generate a list of all the positions of objects that are both within a projected radius and have a specific component.

My code is as follows, and compiles fine, but gets a runtime error stating that the object reference isn’t set to an instance of an object at line 44, the line allyLocations.Add(loc); in the script.

List<Vector2> findSurroundingObjects() {
		Collider[] hitColliders = Physics.OverlapSphere(transform.position, awarenessRadius);
		int i = 0;
		List<Vector2> allyLocations = new List<Vector2>();
		while (i < hitColliders.Length) {
			Vector2 loc = hitColliders*.GetComponentInParent<LocationController>().getCoordinates();*
  •  	allyLocations.Add(loc);*
  •  	i++;*
  •  }*
  •  return allyLocations;*
  • }*

That’s odd, feels like the error should pop up at the GetComponentInParent part.

Anyway what you probably need to do is to add an if condition to check if getcomponent returns a component or null


while (i < hitColliders.Length) {
    private LocationController _locCtrl = hitColliders*.GetComponentInParent<LocationController>();*

if (_locCtrl) {