Hey guys, I’ve been working on a game which has thousands and thousands of gameObjects, and I want them to be destroyed when they leave a certain distance from the player, and reappear where they were when I return. They are randomly generating, and don’t need to store any data besides their position.
I’m just having a really hard time wrapping my head around the way I would go about doing this
The easiest way to handle this would be to create a class. You say:
But there’s one additional thing they do need: a reference to the associated GameObject, if it exists.
public class PositionMarker {
public Vector3 pos;
public GameObject inSceneObject;
}
You can have an array of these which you generate at the start. When you spawn an object, assign the .inSceneObject of the associated PositionMarker. When you loop through to determine which objects need to exist, use inSceneObject != null to determine whether the object at that position has already been spawned.
Addendum #1: Don’t create and destroy large numbers of similar objects; Instantiate is actually a fairly expensive operation, and will cause stuttering if your player moves quickly through the scene. Instead, google for “object pooling” and make or use an object pooling system to deactivate and reactivate objects, moving them to their new PositionMarker. (The above algorithm will still work with very little modification)
Addendum #2: If you need huge numbers of similar objects, you should look into using ECS and DOTS. It’s harder to use but performance in these sorts of situations is truly mindboggling, to the point where you might well be able to actually run thousands and thousands of objects, rather than faking it.