- Home /
Any way to destroy internal classes that were instantiated?
I'm building a script that will instantiate some internal script when called. As in,
 public class Example : MonoBehaviour
 {
    private List<NewClass> newClassList = new List<NewClass>();
   
    public void MakeNewClass()
    {
       newClassList.Add(new SomeClass());
    }
    public void Activate()
    {
       foreach (NewClass class in newClassList) { class.DoSomething(); }
    }
 }
   
 internal class SomeClass : NewClass
 {
    // does something
 }
Now, this function worked just fine... but the thing is, I worry that that would be best practice to do so.
I am creating new class every time NewClass is created via new SomeClass(), but I never get to unload? or destroy? them. Whatever the correct term for that is. I am creating more and more classes without ever removing them, so I worry that this might cause some issue in the future.
Is there anyway I can destroy internal classes? I can't seem to find a way to do that.
I'm not actually entirely sure how C# handles problems like these, as classes don't have destructors. Normally, in C++, you were given the freedom to decide whether to deload your class or not. I'm guessing in C#, it does it automatically for you, if it sees that it isn't being used. I don't know for sure. $$anonymous$$aybe someone else can help, but I wouldn't worry about it for now. If you do get a problem, then I'm sure someone else has already had that issue, and someone has provided a solution for that.
Answer by logicandchaos · Jan 19, 2021 at 07:36 PM
You are talking about a stack overflow, when memory on the stack exceeds available memory. In managed languages like C++ you have to manage memory yourself, C# uses garbage collection, so whatever isn't being used is removed from memory by that. If you want to 'destroy' an instance of a class then set it to null, that should make the GC dispose of it in memory. This is my 250th answer! Thanks!
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
               
 
			 
                