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