Goal: Create nested scriptable objects from the project view.
Expected: When an instance of the container scriptable object is created from the project view, an instance of the child scriptable object is created and attached to the container asset. The container should also keep a reference of the child.
Actual: When I try to attach the child to the container asset, it fails. I use the AssetDatabase.AddObjectToAsset but gives me the following error messages:
- UnityException: Adding asset to object failed.
- AddAssetToSameFile failed because the other asset is not persistent
Observations: The container is created successfully. No child asset is created. The inspector shows a child reference as soon as the asset is created, but says Type mismatch when the name of the container is entered.
The child object is not persistent. I do not know what persistent means in this context. I think this might be the reason I don't understand this problem.
Following is the code of a simplified version of what I am trying to implement. The same error is reproduced.
Container class
[CreateAssetMenu]
public class Container : ScriptableObject
{
[SerializeField] private Child child;
private void Reset()
{
// Create new child
child = ScriptableObject.CreateInstance<Child>();
// Attach child to the container
AssetDatabase.AddObjectToAsset(child, this); // This line throws exception!
// Save changes
AssetDatabase.SaveAssets();
}
}
Child class
public class Child : ScriptableObject
{
[SerializeField] public string myString;
}