Search Unity

ScriptableObject value not persisting after OnImportAsset

Discussion in 'Scripting' started by phxvyper, Jul 9, 2018.

  1. phxvyper

    phxvyper

    Joined:
    Jul 31, 2012
    Posts:
    8
    I have a scripted importer that invokes the following code upon an imported asset:

    Code (CSharp):
    1. var novelObject = ScriptableObject.CreateInstance<NovelObject>();
    2. novelObject.RootNode = walker.Walk();
    3. novelObject.Test = "value";
    4.  
    5. ctx.LogImportWarning($"Test value: {novelObject.Test}");
    6. ctx.LogImportWarning($"RootNode is null: {novelObject.RootNode == null}");
    7.  
    8. ctx.AddObjectToAsset("novel object", novelObject);
    9. ctx.SetMainObject(novelObject);
    With this ScriptableObject being instantiated:

    Code (CSharp):
    1. [Serializable]
    2. public class NovelObject : ScriptableObject
    3. {
    4.     public INovelObject RootNode;
    5.     public string Test;
    6. }
    And later, in a MonoBehaviour attached to a GameObject in my scene, I have:

    Code (CSharp):
    1. public class NovelFrameController : MonoBehaviour
    2. {
    3.     [SerializeField] private NovelObject _novelObject;
    4.  
    5.     private void Start()
    6.     {
    7.         Debug.Log($"Test value: {_novelObject.Test}");
    8.         Debug.Log($"RootNode is null: {_novelObject.RootNode == null}");
    9.     }
    10. }
    Note my calls to ctx.LogImportWarning and Debug.Log.

    After letting this compile, I reimport a test asset and run my game, with the following output:



    At import time, Test and RootNode both have a non-null value. However, at Runtime, the value of RootNode is set to null. Why?
     
  2. MaskedMouse

    MaskedMouse

    Joined:
    Jul 8, 2014
    Posts:
    1,092
    if INovelObject is an interface, Unity can't serialize interfaces by default. It is then cleaned up and null during runtime.