0
votes

I'm trying to destroy any gameobject that is under some height (let's say -5).

I tried foreach method that takes all gameobjects and than compares it using if. If comparison is TRUE, then there is simple Destroy(go);

public float MinimalYLocation; 
GameObject[] Objects;

void Start () {
  Scene scena = SceneManager.GetActiveScene(); 
  Objects = scena.GetRootGameObjects(); 
}

void Update () {
  foreach (GameObject gobject in Objects) {
    float Height = gobject.transform.position.y;
    if (Height < MinimalYLocation){
      Destroy(gobject);
    }
  }
} 

I set up a scene that contains 3 cubes in different heights and a camera. Script is in camera. When first cube falls, it is destroyed. Then I get massive spam to console:

MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it.

And the second and third cubes are not destroyed. Expected response would be that all gameobjects will be destroyed as they touch height -5

1
When you "Destroy()" a game object ... then you ALSO need to remove it from your "Objects" list.paulsm4

1 Answers

5
votes

This is not going to be a scalable approach. You will find that it has a severe impact on your game's performance as more and more GameObjects are active in the scene.

I recommend you add a plane that extends to all game area bounds, and sits at this "-5" z position. Give the plane a collider trigger and destroy all objects that touch it. Leave the plane without a texture (aka invisible).

This will eliminate what is going to be a massive load in an update that happens every single frame.