So for a while now (probably since AssetDatabase v2) There’s been some weird things going on with sub assets, AddObjectToAsset, RemoveObjectFromAsset and ImportAsset.
in 2019.3 - 2020.1 (Case #1262298) Sub assets don’t appear in the project view until they are “pinged” and project is manually saved.
in 2020.2 (Case #1262293) Sub assets appear immediately, but a warning appears similar to this:
Importer(NativeFormatImporter) generated inconsistent result for asset when adding SubAsset
Documentation says: Unity - Scripting API: AssetDatabase.AddObjectToAsset
- Create the sub asset
- Add the sub asset
- Import main asset
This used to work flawlessly before AssetDatabase V2.
Here’s the code I used to submit the reports:
using UnityEditor;
using UnityEngine;
public static class AssetUtil {
#region Public Methods
public static T CreateSubAsset<T>(string path, SerializedProperty list) where T : ScriptableObject {
//create new instance of T
T asset = ScriptableObject.CreateInstance<T>();
asset.name = $"Child {list.arraySize}";
//undo support
Undo.RegisterCreatedObjectUndo(asset, $"Create {typeof(T).Name} Asset");
//add the asset as a sub asset to path
AddObjectToAsset(asset, path, list);
return asset;
}
public static void AddObjectToAsset(Object asset, string path, SerializedProperty list) {
//add the object to path
AssetDatabase.AddObjectToAsset(asset, path);
//increase list and reference
list.arraySize++;
list.GetArrayElementAtIndex(list.arraySize - 1).objectReferenceValue = asset;
list.serializedObject.ApplyModifiedProperties();
//Does not refresh the MainAsset in 2019.3 - 2020.1
//Warning in 2020.2 - Importer(NativeFormatImporter) generated inconsistent result for asset when adding SubAsset
AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
}
public static void RemoveObjectFromAsset(int index, string path, SerializedProperty list) {
//get the asset on the list
SerializedProperty property = list.GetArrayElementAtIndex(index);
Object asset = property.objectReferenceValue;
if (asset) {
//remove asset, **this seems to also handle Undo?** Not mentioned in documentation, so a little skeptical :|
AssetDatabase.RemoveObjectFromAsset(asset);
//null the reference and remove from list
property.objectReferenceValue = default;
list.DeleteArrayElementAtIndex(index);
list.serializedObject.ApplyModifiedProperties();
//Does not refresh the MainAsset in 2019.3 - 2020.1
//Warning in 2020.2 - Importer(NativeFormatImporter) generated inconsistent result for asset when adding SubAsset
AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
}
}
#endregion
}
Just wondering… Is there some new approach to adding sub assets? Or Unity are aware and fixing?
Does the above code look valid?