Add a GameObject as a sub-asset of a ScriptableObject

I am trying to add a GameObject as a sub-asset of a ScriptableObject.

Try #1
I have tried to do it that way :

GameObject go = new GameObject("object name");
go.hideFlags = HideFlags.HideInHierarchy;
AssetDatabase.AddObjectToAsset(go, myAsset);

but when I press Play, I get those errors :

  1. Can’t destroy Transform component of ‘object name’. If you want to destroy the game object, please call ‘Destroy’ on the game object instead. Destroying the transform component is not allowed.

  2. Some objects were not cleaned up when closing the scene. (Did you spawn new GameObjects from OnDestroy?)

Try #2
and that way :

GameObject go= new GameObject("object name");
GameObject prefab = PrefabUtility.CreatePrefab("Assets/temp.prefab", go);
prefab.hideFlags = HideFlags.HideInHierarchy;
AssetDatabase.AddObjectToAsset(prefab, myAsset);

With this code, I get an error on the call to AssetDatabase.AddObjectToAsset :

  • You may not change the path if an object is already peristent in another one

Is it possible to add a gameobject (as a prefab or not) as a sub-asset of a ScriptableObject?

It could be difficult.

A prefab is another asset, hence the error that the object path can’t be changed. It might be the case that a prefab, internally, works by storing each of the components that exist on the GameObject instead of the GameObject itself. This would make sense, and produce the error you saw upon trying to add the prefab to another asset.

You may be able to iterate through each component and add it separately to the asset, and then instantiate the GameObject from that.

I’d imagine that it would be easier to just have prefab assets exist beside your custom asset, and store a reference to the prefab. I believe this should work. If referencing the prefab explicitly doesn’t work, then maybe reference by it’s path and use ISerializationCallbackReceiver to load the GameObject upon Deserialization.