Search Unity

Is it safe to destroy a GameObject in a C# destructor?

Discussion in 'Editor & General Support' started by sollniss, Aug 20, 2019.

  1. sollniss

    sollniss

    Joined:
    Aug 23, 2017
    Posts:
    11
    Hello,
    I have a class that creates a GameObject in it's constructor. Would it be fine if I call

    Code (CSharp):
    1. ~MyClass()
    2. {
    3.      GameObject.Destroy(go); // DestroyImmediate ?
    4. }
    or should I make an explict .Dispose() method?
     
  2. Xarbrough

    Xarbrough

    Joined:
    Dec 11, 2014
    Posts:
    1,188
    You should use a Dispose method which you call on the main thread. Either directly of via the “using” construct. The finalizer in C# will only be called by the Garbage Collector, which most likely happens on a different threas and you have only limited control over when and if this ever happens.