- Home /
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 :
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.
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?
myAsset in the previous code samples is a ScriptableObject.
Answer by mintman · Feb 06, 2015 at 01:31 PM
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.
It would be easier to point to prefabs saved elsewhere but unfortunately this is not a solution I would like to consider, since the prefabs are hidden from the user and should not be edited/renamed/deleted by user.
That makes a lot of sense. Since you need to put a prefab in an asset you may need to add each component separately, and write some code to instantiate a game object from the components you stored.
I've never tried adding components into an asset myself, but I imagine it would work. That would be something to test before trying my suggestion above.
Good luck!
Unity does not allow the creation of components without having a game object.
Your answer
![](https://koobas.hobune.stream/wayback/20220613164323im_/https://answers.unity.com/themes/thub/images/avi.jpg)