- Home /
How can Editor Script change value in a Prefab instance ?
I have a prefab with a string call CAKE initialized to APPLE in one of its component. I copy an instance of the prefab as one GameObject in the Hierarchy window. Then I use an editor script to modify the value to BANANA before the game is started.
In the inspector window, the value is correctly updated but not in bold.
When I start the game, it returns old value Apple.
If I modify the value manually in the inspector window, and start the game, it returns good value BANANA.
How can I update correcty the value using EDITOR SCRIPT ?
//PREFAB
public class DecorController : MonoBehaviour
{
public string CAKE = "APPLE";
}
//EDITOR SCRIPT
[CustomEditor(typeof(DecorController))]
public class DecorControllerEditor : Editor
{
SerializedProperty m_CAKE;
void OnEnable()
{
m_CAKE = serializedObject.FindProperty("CAKE");
}
public override void OnInspectorGUI()
{
serializedObject.Update();
EditorGUILayout.PropertyField(m_CAKE);
serializedObject.ApplyModifiedProperties();
}
void OnSceneGUI()
{
DecorController myController = (DecorController)target;
myController.CAKE = "BANANA";
}
}
Answer by sudoku1v2 · Feb 20, 2021 at 04:48 AM
I find this on forums ,and after some tries it works. You have to use serialized properties.
void OnSceneGUI()
{
DecorController myController = (DecorController)target;
var newserializedObject = new SerializedObject(myController);
newserializedObject.Update();
SerializedProperty _featuresProperty = newserializedObject.FindProperty("CAKE");
_featuresProperty.stringValue = "BANANA";
newserializedObject.ApplyModifiedProperties();
}
Your answer
Follow this Question
Related Questions
Setting the m_PrefabInternal property using the SeriailizedProperty System 0 Answers
Unity UI 4.6 - Programmatically adding events - EventTrigger.delegates is null 0 Answers
How to add a component on a GameObject in Custom Inspector 1 Answer
Make the Inspector only show a specific CustomEditor 1 Answer