c# - 如何从 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...");
}
}
解决方案
我不建议使用直接更改值
Test myTest = (Test)target;
myTest.value = EditorGUI.TextField(textFieldRect, myTest.value);
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.ExpandWidth
和GUILayout.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);
推荐阅读
- postgresql - 迁移 PostgreSQL JSON 中弄乱的 UTF-8 字符代码
- php - 如何在订单管理页面的自定义列中添加自定义文本字段
- r - 使用 ggplot2 设置 Voronoi 单元的最大大小
- c# - 具有返回值的函数字典 C#
- scala - 在 Scala 中打印时从元组中删除数据类型
- powershell - 在文件中查找字符串并用另一个文件中的值替换多行 - powershell
- javascript - 问题:Fullcalendar 将 24 显示为午夜而不是 00:00
- javascript - 使用 touchmove 事件检测哪个 div 手指结束
- docker - 在 docker-compose up 之后添加音量
- javascript - 我想为从 mysql 数据库登录的每个用户发送唯一记录