首页 > 解决方案 > 如何从 Unity 中的自定义编辑器脚本修改序列化变量

问题描述

我有一个带有 1 个序列化字符串的测试脚本,我试图通过在 TextField 中输入一些内容来访问和修改它,但我不知道将 TextField 分配给什么。

测试脚本:

using UnityEngine;

public class Test : MonoBehaviour
{
    [SerializeField] private string value;

}

测试工具脚本:

using UnityEngine;
using UnityEditor;

[CustomEditor(typeof(Test))]
public class TestTool : Editor
{
[ExecuteInEditMode]
public override void OnInspectorGUI()
{

    base.OnInspectorGUI();

    Rect textFieldRect = new Rect(EditorGUILayout.GetControlRect(false, EditorGUIUtility.currentViewWidth));

    EditorGUI.DrawRect(textFieldRect, Color.gray);

    EditorGUI.TextField(textFieldRect, "Type here...");
}
}

在此处输入图像描述

在此处输入图像描述

标签: c#user-interfaceunity3deditor

解决方案


建议使用直接更改值

Test myTest = (Test)target;
myTest.value = EditorGUI.TextField(textFieldRect, myTest.value);

而是使用SerializedProperty

private SerializedProperty _value;

private void OnEnable()
{
    // Link the SerializedProperty to the variable 
    _value = serializedObject.FindProperty("value");
}

public override OnInspectorGUI()
{
    // fetch current values from the target
    serializedObject.Update();

    EditorGUI.PropertyField(textFieldRect, _value);

    // Apply values to the target
    serializedObject.ApplyModifiedValues();
}

这样做的巨大优势是撤消/重做以及将场景和类标记为“脏”都是自动处理的,您不必手动进行。

但是,要使这项工作变量始终是public或者[SerializedField]在您的班级中已经是这种情况。

而不是rect我实际上建议您使用EditorGUILayout.PropertyField和设置大小通过GUILayout.ExpandWidthGUILayout.ExpandHeight/或其他可用的

选项

GUILayout.Width、GUILayout.Height、GUILayout.MinWidth、GUILayout.MaxWidth、GUILayout.MinHeight、GUILayout.MaxHeight、GUILayout.ExpandWidth、GUILayout.ExpandHeight。

为了不显示标签,请使用GUIContent.none.

所以它可能看起来像

EditorGUILayout.PropertyField(_value, GUIContent.none, GUILayout.ExpandHeight, GUILayout.ExpandWith);

推荐阅读