OnDestroy-like function for non monobehaviour

Hello everyone, Im wondering if there’s a way to mimic the OnDestroy function on monobehaviour for regular class. for example

i want to count how many instance of this class.

public class MyClass {
public static int MyClassCounter;

public MyClass() {
	MyClassCounter++;
}

public OnDestroy() {
	// will be called when Garbage Collector collects it ?
	MyClassCounter--;
}

}

Thank you. :slight_smile:

2 Answers

2

You can use a destructor.

You could try implementing IDisposable interface.

public class MyClass : IDisposable {
    public static int MyClassCounter;

    public MyClass() {
        MyClassCounter++;
    }

    public void Dispose() {
        // release unmanaged resources, if any
        MyClassCounter--;
    }
}

It should be called on garbage collection.