Debris doesn't get destroyed

I had this fun idea of making pretty primitive Voxels. To make up a somewhat destructible world. To do this, I constructed a 3x3 box first that is constructed of a lot of smaller boxes to make it look like one box. I know it’s not the best approach, but perhaps you could advise on a better solution? Instanced Meshes or something?

So what I set out to do was to make a system that made sure there weren’t too many meshes on screen at once as to not kill weaker computers. My system is simple. It looks like this:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class GlobalDebrisManager : MonoBehaviour
{
    public int DebrisThreshold;
    private static Stack<GameObject> debris;
    public static GlobalDebrisManager instance;

    public void Awake()
    {
        if (instance != null && instance != this)
        {
            Destroy(this.gameObject);
            return;
        }
        else
        {
            instance = this;
            debris = new Stack<GameObject>();
        }
        DontDestroyOnLoad(this.gameObject);
    }

    public static void AddDebris(GameObject obj)
    {
        if (debris.Count < instance.DebrisThreshold)
        {
            debris.Push(obj);
        }
        else
        {
            GameObject gObj = debris.Pop();
            gObj.GetComponent<BoxCollider>().enabled = false;
            instance.DestroyDebris(gObj);
            debris.Push(obj);
        }
    }

    IEnumerator DestroyDebris(GameObject obj)
    {
        yield return new WaitForSeconds(1.5f);
        Destroy(obj);
    }
}

This class is solely responsible for keeping track of all debris blocks in the level that needs to be active. The rest of the blocks will simply fall through the world and be destroyed. Or at least, that’s the idea. If you look below you’ll see +200 blocks flying. The threshold value is set to 150 blocks Max. I used a stack because I thought it would be an easy thing to simple call “Push” and “Pop” whenever I wanted to push a new object in (newest piece of debris) and pop out the oldest piece of debris. So that new pieces stay and old pieces disappear.

But none of my gameobjects get destroyed. They just stay in the world. What am I doing wrong?

Change line 36 from
instance.DestroyDebris(gObj);
to
StartCoroutine(instance.DestroyDebris(gObj));

It won’t let me call “StartCoroutine” from a static method

Ah, yes, didn’t notice your method was static. You can either make the method instanced (no reason to have it static, since it relies on your instance anyway), or use this line:
instance.StartCoroutine(instance.DestroyDebris(gObj));

1 Like

Oh yeah, you are right. I just made the method public instead of static public. So I can call “AddDebris()” through the instance instead and use StartCoroutine() :slight_smile:

Thanks