Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Ordering of scriptable objects added in asset with AssetDatabase.AddObjectToAsset

Discussion in 'Asset Database' started by maxxa05, Aug 18, 2016.

  1. maxxa05

    maxxa05

    Joined:
    Nov 17, 2012
    Posts:
    186
    So, I made a simple example to test AssetDatabase.AddObjectToAsset. All is serializing perfectly, but I've got a weird issue with the ordering. Everytime I add another ScriptableObject to my asset and reimport it, it becomes the new root of my asset. The original root of the asset becomes a child, like that:

    Test.png

    Here's my code:

    Code (csharp):
    1. using UnityEngine;
    2.  
    3. public class TestParentSO : ScriptableObject
    4. {
    5.     public TestChildSO[] children;
    6. }
    Code (csharp):
    1. using UnityEngine;
    2.  
    3. public class TestChildSO : ScriptableObject
    4. {
    5.     public int value = 5;
    6. }
    Code (csharp):
    1. using UnityEngine;
    2. using System.Collections.Generic;
    3. using UnityEditor;
    4.  
    5. [CustomEditor(typeof(TestParentSO))]
    6. public class TestEditor : Editor
    7. {
    8.     public override void OnInspectorGUI()
    9.     {
    10.         base.OnInspectorGUI();
    11.         var parent = (TestParentSO) target;
    12.         List<TestChildSO> children = new List<TestChildSO>();
    13.         if (GUILayout.Button("Populate"))
    14.         {
    15.             for (int i = 0; i < 5; i++)
    16.             {
    17.                 var child = CreateInstance<TestChildSO>();
    18.                 AssetDatabase.AddObjectToAsset(child, parent);
    19.                 children.Add(child);
    20.                    
    21.             }
    22.             serializedObject.Update();
    23.  
    24.             //Method to assign a list to a SerializedProperty Array. Not the issue here
    25.             SerializedObjectUtil.AssignArrayProperty
    26.                 (serializedObject.FindProperty("children"), children);
    27.             serializedObject.ApplyModifiedProperties();
    28.             AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(parent));
    29.         }
    30.     }
    31. }
     
  2. maxxa05

    maxxa05

    Joined:
    Nov 17, 2012
    Posts:
    186
    It does the same thing in 5.3 and 5.4, so it seems it's not related to a specific version of Unity.
     
  3. maxxa05

    maxxa05

    Joined:
    Nov 17, 2012
    Posts:
    186
    I found that using hideFlags = HideFlags.HideInHierarchy on the children seems to at least prevent the problem, but now it's impossible to select them in the Project hierarchy. Being able to see them, but in an order that makes sense, would be really nice.