Search Unity

  1. Unity Asset Manager is now available in public beta. Try it out now and join the conversation here in the forums.
    Dismiss Notice
  2. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  3. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Bug Objects added to AssetImportContext in a ScriptedImporter don't get destroyed.

Discussion in 'Experimental Scripting Previews' started by rohan_zatun, Aug 27, 2021.

  1. rohan_zatun

    rohan_zatun

    Joined:
    Aug 18, 2021
    Posts:
    6
    Hello,
    this is my code:
    Code (CSharp):
    1.  
    2. public class SO : ScriptableObject
    3. {
    4.     public string text;
    5. }
    6.  
    Code (CSharp):
    1.  
    2. [ScriptedImporter(1, "xyz")]
    3. public class SOI : ScriptedImporter
    4. {
    5.     public override void OnImportAsset(AssetImportContext ctx)
    6.     {
    7.         var obj = AssetDatabase.LoadMainAssetAtPath(ctx.assetPath);
    8.         if (obj == null) // always null
    9.         {
    10.             obj = ScriptableObject.CreateInstance<SO>();
    11.             ctx.AddObjectToAsset("SO", obj);
    12.             ctx.SetMainObject(obj);
    13.         }
    14.  
    15.         obj.text = File.ReadAllText(ctx.assetPath);
    16.     }
    17. }
    18.  
    The issue here is that whenever the *.xyz file gets updated, the OnImportAsset function is called but there are two issues, which aren't an issue by themselves, but together they're a bug.
    1. Whenever you call LoadMainAssetAtPath, it does not return existing object. It always returns null.
    2. The previous object originally added to the asset is never destroyed. This causes problems with objects that require disposing resources on OnDisable/OnDestroy (neither of these messages are called).

    What I want to have is a NativeArray that I dispose in OnDisable (which I suppose occurs upon reimports and and recreate in OnEnable but I can't do that, and it's just going to cause a resource leak because the lifecycle-end callbacks don't occur.