Assigning a dynamically created prefab to a ScriptableObject


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!

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/" + + ".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/" + + ".asset");
		AssetDatabase.SaveAssets ();

		EditorUtility.FocusProjectWindow ();
		Selection.activeObject = platform;


AssetDatabase.AddObjectToAsset(prefab, platform);