- Home /
Assigning a dynamically created prefab to a ScriptableObject
Hello,
I'm creating some tools in the editor to make life easier, but I've run into a road block. I'm procedurally generating a prefab and a ScriptableObject based on a GameObject that I've selected in the scene when I'm working. (it's for platform generation/creation)
The method gets called via a menu item link.
When I assign the newly created prefab to the ScriptableObject field that holds the reference to the prefab (in code), it attaches it to the GameObject in the scene, and not the Prefab in the Asset Database. And the inspector says "mismatch type".
Does anybody know how to do this? I'm trying to remove the step of dragging and dropping the prefab into the ScriptableObject every time because I'm going to be doing this a lot.
EDIT: The code being executed is in the #if UNITY_EDITOR namespace so instantiate will not work.
Thank you!
Answer by TeftyTeft · Aug 21, 2014 at 09:22 PM
Okay, I figured it out and wanted to share for anybody running into the same problem.
You have to reload the saved prefab using AssetDatabase.LoadAssetAtPath and reference that GameObject for your ScriptableObject instance.
string prefabLocation = "Assets/prefabSaveLocation/" + Selection.activeGameObject.name + ".prefab";
Object prefab = PrefabUtility.CreateEmptyPrefab(prefabLocation);
PrefabUtility.ReplacePrefab(Selection.activeGameObject, prefab, ReplacePrefabOptions.ConnectToPrefab);
CustomObject platform = ScriptableObject.CreateInstance<CustomObject> ();
GameObject prefabLoad = AssetDatabase.LoadAssetAtPath (prefabLocation, typeof(GameObject)) as GameObject;
platform.platformPrefab = prefabLoad;
AssetDatabase.CreateAsset (platform, "Assets/scriptableObjectLocation/" + Selection.activeGameObject.name + ".asset");
AssetDatabase.SaveAssets ();
EditorUtility.FocusProjectWindow ();
Selection.activeObject = platform;
`
Answer by winxalex · Feb 14, 2018 at 02:22 PM
AssetDatabase.AddObjectToAsset(prefab, platform);
platform.platformPrefab=prefab;
Your answer
Follow this Question
Related Questions
Referencing / linking a .asset / .prefab file in another .asset / .prefab file programmatically. 2 Answers
How to know if something is selected in Hierarchy or in project. 5 Answers
How to set a shared material in inspector? 0 Answers
How do I get the default scene GUI for a CustomEditor for RectTransform? 1 Answer
Can I force z position to match prefab when it's dragged onto scene? 1 Answer