Search Unity

References to sub-objects get lost on re-import

Discussion in 'Experimental Scripting Previews' started by Solovykh, May 4, 2020.

  1. Solovykh

    Solovykh

    Joined:
    Aug 28, 2017
    Posts:
    59
    Hi there,

    I'm not sure if this is a known problem but if I have a a nested scriptable object and I reference it from a monobehaviour, that reference breaks as soon as the scriptable object gets re-imported.

    In more detail, I have a scriptable object like this:

    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class TestScriptableObject : ScriptableObject
    4. {
    5. }
    6.  
    And I create a nested scriptable object like this:
    Code (CSharp):
    1. using UnityEditor.Experimental.AssetImporters;
    2. using UnityEngine;
    3.  
    4. [ScriptedImporter(1, ".test")]
    5. public class TestImporter : ScriptedImporter
    6. {
    7.     public override void OnImportAsset(AssetImportContext context)
    8.     {
    9.         TestScriptableObject mainScriptableObject = ScriptableObject.CreateInstance<TestScriptableObject>();
    10.         mainScriptableObject.name = "Main Object";
    11.    
    12.         TestScriptableObject nestedScriptableObject = ScriptableObject.CreateInstance<TestScriptableObject>();
    13.         nestedScriptableObject.name = "Nested Object";
    14.    
    15.         context.AddObjectToAsset(nestedScriptableObject.GetHashCode().ToString(), nestedScriptableObject);
    16.         context.AddObjectToAsset("main", mainScriptableObject);
    17.         context.SetMainObject(mainScriptableObject);
    18.     }
    19. }
    Then, I reference that "Nested Object" in a monobehaviour like this:
    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class TestMonoBehaviour : MonoBehaviour
    4. {
    5.     public TestScriptableObject testReference;
    6. }
    7.  
    That testReference breaks anytime the nested scriptableobject gets reimported.

    I should mention I'm running 2019.3.12f1

    I submitted a bug report: 1244204
     
    Last edited: May 4, 2020
  2. M_R

    M_R

    Joined:
    Apr 15, 2015
    Posts:
    554
    that's because
    nestedScriptableObject.GetHashCode()
    is different every time you create it, and you use it as an identifier. try a stable identifier (e.g. "nested")
     
    Solovykh likes this.
  3. Solovykh

    Solovykh

    Joined:
    Aug 28, 2017
    Posts:
    59
    Yep, that was it. Thank you! I thought hash code was generated via a hash function from the name of the object. But I guess not. Thanks again.
     
unityunity