Question by
valentinregnault22 · Feb 14, 2021 at 11:41 AM ·
prefabunityeditoreditor-scriptingcomponenteditorwindow
How to add a component from a Custom Editor object field to a Prefab ?
Hey, I saw in this post how to make a Prefab in a CustomEditor script. My question is how do I add a component that I get in a ObjectField to a Prefab ?
var Script = EditorGUILayout.ObjectField(Script, typeof(Object), true); //get the script
var tempGO = new GameObject();
// add a script to it
var tempComponent = tempGO.AddComponent(Script) // <--- I'm looking for something like this
// give the script the values from input (note: values on the script needs to be public)
tempComponent.someValue = someInputValue;
tempComponent.someValue2 = someInputValue2;
// create an empty prefab in project
var emptyPrefab = PrefabUtility.CreateEmptyPrefab(full path to save including prefab name);
// replace the gameobject with the empty prefab (save)
PrefabUtility.ReplacePrefab(tempGO, emptyPrefab);
Comment
Best Answer
Answer by valentinregnault22 · Feb 14, 2021 at 01:43 PM
Solved : var tempComponent = tempGO.AddComponent(Script.GetType())
if you want to set properties of a base class: var tempComponent = (BaseClass) tempGO.AddComponent(Script.GetType())