Destroy(this)???

Hi,
Suppose I have a List of objects of a class type, and IN that class, I create an Update() function inside the class with code in it so that each object or list of objects destroys itself 5 seconds after construction. Wouldn’t making Destroy(this) possible be a good idea for something like that? What would also REALLY be a good idea is to have a way where code could be written so that the list ‘removes’ each element after 5 seconds since destroying the element I believe makes it null or missing.

Could you add the object to the list when it is spawned & have a timer on the object that says after 5 seconds remove it from list A & add it to list B? Or are you talking about pooling?

Give the “Manager” Class that contains the List a public static Method for Adding and Removing Items from that list.
On the Gamobjects, you call said Methods on Start and OnDestroy to either add or remove.

Example of what garrido86 means (errors are expected as notepad++ does not have intellisense):

public class DestroyMe : MonoBehaviour
{
    void Start()
    {
        Manager.Add(this);
    }
   
    void Update()
    {
        // Check some arbitrary timer and then
        Destroy(gameObject);
    }
   
    void OnDestroy()
    {
        Manager.Remove(this);
    }
}

public static class Manager : MonoBehaviour
{
    private List<DestroyMe> _list = new List<DestroyMe>();
   
    public static void Add(DestroyMe thing)
    {
        _list.Add(thing);
    }
   
    public static void Remove(DestroyMe thing)
    {
        _list.Remove(thing);
    }
}

However, depending on what you do with the items, pooling might be a better idea: http://unity3d.com/learn/tutorials/modules/beginner/live-training-archive/object-pooling

1 Like

Do all of that. Except don’t make the methods static.

It’s also worth pointing out that Destroy takes an optional second parameter. This is a float that specifies the time to destruction. Calling it once in Start beats calling it in Update.

1 Like

Updated code as per BoredMormon’s recommendations:

public class DestroyMe : MonoBehaviour
{
    private object _manager;
 
    void Start()
    {
        _manager = (Manager)FindObjectOfType(typeof(Manager));
        _manager.Add(this);
     
        Destroy(gameObject, 5.0f);
    }
 
    void OnDestroy()
    {
        _manager.Remove(this);
    }
}

public class Manager : MonoBehaviour
{
    private List<DestroyMe> _list = new List<DestroyMe>();
 
    public void Add(DestroyMe thing)
    {
        _list.Add(thing);
    }
 
    public void Remove(DestroyMe thing)
    {
        _list.Remove(thing);
    }
}

To be clear, I have let out quite a lot of null check and potential error handling out of this code, so make sure to not use it 1:1 without adding it as it can save you a lot of headaches later on. This also ensures you’ll work with the code so you learn it well :slight_smile:

1 Like