Search Unity

Do I have to call SerializedObject.Dispose when creating a custom SerializedObject?

Discussion in 'Scripting' started by Xarbrough, Jun 19, 2019.

  1. Xarbrough

    Xarbrough

    Joined:
    Dec 11, 2014
    Posts:
    1,188
    There are a couple of tools I've built which modify other components like this:

    Code (CSharp):
    1. var so = new SerializedObject(someOtherComponent);
    2. so.FindProperty("someProp").intValue = 2;
    3. so.ApplyModifiedProperties();
    4. so.Dispose(); // Is this required or recommended?
    I create a SerializedObject for the target, then find a property and modify it. I like this approach because it lets me modify private variables and also supports Undo, etc. This works well for batch-processing GameObjects without using any sort of visual custom inspector.

    However, I noticed that there is a undocumented Dispose method on the SerializedObject class. Do I have to call this when I'm done using it? Will it leak memory otherwise? My current project is crashing pretty often and I wonder if it could be because of some uncleaned objects like this.
     
    Celezt likes this.
  2. Kwinten

    Kwinten

    Joined:
    Jan 25, 2015
    Posts:
    49
    If you look here: https://github.com/Unity-Technologi...ster/Editor/Mono/SerializedObject.bindings.cs

    A SerializedObject will automatically call the Dispose method when it is garbage collected (which is when its destructor function is called).
    So I would say you can manually call Dispose as well, but only if you really want to have manual control over how Unity internally keeps these objects in memory. Otherwise I would just let the garbage collector do its job.
     
    Celezt and Xarbrough like this.