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:
Here’s my code:
using UnityEngine;
public class TestParentSO : ScriptableObject
{
public TestChildSO[] children;
}
using UnityEngine;
public class TestChildSO : ScriptableObject
{
public int value = 5;
}
using UnityEngine;
using System.Collections.Generic;
using UnityEditor;
[CustomEditor(typeof(TestParentSO))]
public class TestEditor : Editor
{
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
var parent = (TestParentSO) target;
List<TestChildSO> children = new List<TestChildSO>();
if (GUILayout.Button("Populate"))
{
for (int i = 0; i < 5; i++)
{
var child = CreateInstance<TestChildSO>();
AssetDatabase.AddObjectToAsset(child, parent);
children.Add(child);
}
serializedObject.Update();
//Method to assign a list to a SerializedProperty Array. Not the issue here
SerializedObjectUtil.AssignArrayProperty
(serializedObject.FindProperty("children"), children);
serializedObject.ApplyModifiedProperties();
AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(parent));
}
}
}