- Home /
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?
Answer by Julien-Lynge · Mar 01, 2013 at 02:02 AM
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.
Yeah I typed out that code just to avoid someone saying "you didn't declare nearbyObjects" - it's not meant to be there twice.
Anyway I don't know if the objects have parents, they're just cubes from the editor, so how do I get the gameObject without a parent? Just tempObj.transform.gameObject?
I just removed the .parent. and now it works! Thank you!
Your answer
Follow this Question
Related Questions
How to create an array of Transforms 1 Answer
How to remove objects from a list ? 3 Answers
Can't add GameObjects to ArrayList 1 Answer
Keep adding targets to a list 2 Answers