How To Get A Reference To All Nearby GameObjects?

I’m trying to get an array of all the nearby GameObjects, so I did this:

List<GameObject> nearbyObjects nearbyObjects = new List<GameObject>();

float boxLength = minBoxLength + (speed/maxSpeed) * minBoxLength;
		
Collider[] tempNearbyObjects = Physics.OverlapSphere (transform.position, boxLength);
		
foreach(Collider tempObj in tempNearbyObjects)
{
nearbyObjects.Add(tempObj.transform.parent.gameObject);
}

But I get a null reference error, which would imply that the tempNearbyObjects array is empty but when I print the length, it’s length is 4. (which is how many objects are near that point so it’s working).

Is there a problem with how I’m getting the gameObject from the Collider?

This line does not work:

List<GameObject> nearbyObjects nearbyObjects = new List<GameObject>();

did you type in your code, rather than copying and pasting it?

I’m guessing this is the line that’s throwing the error:

nearbyObjects.Add(tempObj.transform.parent.gameObject);

You are making the assumption that every tempObj has a parent - that is probably not a wise assumption.