Specify all GameObjects?

Viewed 33

I was wondering if there was a way to specify all game objects. I am trying to calculate the distance between the player and the grounds/every game object but the player and what it's made up of. anyway, if anyone knows how to get the distance of the nearest gameobject to the player please let me know.

1 Answers

You can get all GameObjects in your Scene using GameObject.FindGameObjectsOfType<GameObject>() because this will get every GameObject that is a GameObject, meaning everyone.

If you also want to get inactive GameObjects, you can use GameObject.FindGameObjectsOfType<GameObject>(true)

However, I don't think you really want every GameObject. You probably either want everyone that has a collider or everyone that has a Renderer.

If you want to get all GameObjects with a Collider, you can use GameObject.FindGameObjectsOfType<Collider>() for 3D Colliders or GameObject.FindGameObjectsOfType<Collider2D>() for 2D Colliders

If you want to get all GameObjects wich are being rendered, you can use GameObject.FindGameObjectsOfType<Renderer>().

Of course, you can put true between the parentheses of all of these to get inactive ones too.

However

It's generally not a good idea to get so many objects because it's very bad for performance.

Related