如何从Unity中的自定义编辑器脚本修改序列化变量

时间:2018-11-09 19:55:56

标签: c# user-interface unity3d editor

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

测试脚本:

Sub MassTEST()



Dim ws As Worksheet: Set ws = ActiveSheet
Dim cel As Range
Dim VRange1 As String
Dim VRange2 As String
Dim Doublecheck As Integer


VRange1 = InputBox("Enter First Cell Address Here" & vbNewLine & vbNewLine & "Make sure you ONLY input a single cell address")

VRange2 = InputBox("Enter Second Cell Address Here" & vbNewLine & vbNewLine & "Make sure you ONLY input a single cell address")

Data = ws.Range(VRange1, VRange2).Value

For Each cel In ws.UsedRange
    If cel.Value <> "" Then
        cel.Value = 1
    Else
        cel.Value = 0
    End If
Next

TestTool脚本:

using UnityEngine;

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

}

enter image description here

enter image description here

2 个答案:

答案 0 :(得分:1)

建议直接使用来更改值

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();
}

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

然而,使该工作变量始终必须为public[SerializedField],这在您的班级中已经如此。

我实际上建议您使用EditorGUILayout.PropertyField而不是rect并通过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);

答案 1 :(得分:0)

此:

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

target是通过Editor超类提供的属性,并且包含对要检查的任何对象实例的引用。