Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
86 views
in Technique[技术] by (71.8m points)

c# - Unity resets parameter value set with Editor script on play

I've set up a very simple Editor script in Unity 2020.2.1f1 that, upon pressing an Inspector button, should change the value of a specified parameter to a value set in the code.

public override void OnInspectorGUI()
{
    DrawDefaultInspector();

    StateObject s = (StateObject)target;
    if (s.objID == 0)
    {
        if (GUILayout.Button("Generate Object ID"))
        {
            GenerateID(s);
        }
    }
}

public void GenerateID(StateObject s)
{
    s.objID = DateTimeOffset.Now.ToUnixTimeSeconds();
}

This all works like it's supposed to. I press the button, the correct number appears in the field, and I'm happy. However, once I switch to Play mode, the value resets to the prefab default and remains that way even when I switch Play mode off.

Am I missing some ApplyChange function or something?

question from:https://stackoverflow.com/questions/65872685/unity-resets-parameter-value-set-with-editor-script-on-play

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In my eyes better than mixing in direct accesses from Editor scripts and then manually mark things dirty rather go through SerializedProperty and let the Inspector handle it all (also the marking dirty and saving changes, handle undo/redo etc)

SerializedProperty id;

private void OnEnable()
{
    id = serializedObject.FindProperty("objID");
}

public override void OnInspectorGUI()
{
    DrawDefaultInspector();

    // Loads the actual values into the serialized properties
    // See https://docs.unity3d.com/ScriptReference/SerializedObject.Update.html
    serializedObject.Update();

    if (id.intValue == 0)
    {
        if (GUILayout.Button("Generate Object ID"))
        {
            id.intValue = DateTimeOffset.Now.ToUnixTimeSeconds();
        }
    }

    // Writes back modified properties into the actual class
    // Handles all marking dirty, undo/redo, etc
    // See https://docs.unity3d.com/ScriptReference/SerializedObject.ApplyModifiedProperties.html
    serializedObject.ApplyModifiedProperties();

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...