无法保存编辑器脚本的变量



大家好,我正在尝试保存一个自定义编辑器值设置在组合框中的字段,我从互联网上得到了一段代码,但我意识到组合框中所做的更改根本无法保存,我尝试使用"保存"按钮,我尝试制作serializedfield,但我是C#和unity的新手。谢谢你的来访祝你今天愉快。

using UnityEditor;
using UnityEngine;

[CustomEditor(typeof(DoorScript))]
[System.Serializable]
public class ButtonDropDownMenu : Editor
{
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
DoorScript script = (DoorScript)target;
GUIContent arrayLabel = new GUIContent("Color");
script.index = EditorGUILayout.Popup(arrayLabel, script.index, script.options);
/*serializedObject.FindProperty("index").intValue = script.index = EditorGUILayout.Popup(arrayLabel, script.index, script.options);
script.index = EditorGUILayout.Popup(arrayLabel, script.index, script.options);
var properlyToSave = serializedObject.FindProperty("Index");
EditorGUILayout.PropertyField(properlyToSave);
serializedObject.ApplyModifiedProperties();¨*/
}
}

using UnityEngine;
using UnityEngine.Experimental.Rendering.Universal;
public class DoorScript : MonoBehaviour
{
private SpriteRenderer myColor;
public Light2D doorLight;
public Light2D doorPLight;
[HideInInspector][SerializeField]
public int index = 0;
[HideInInspector][SerializeField]
public string[] options = new string[]
{
"White",
"Red",
"Blue",
"Cyan"
};
private void Awake()
{
myColor = GetComponent<SpriteRenderer>();
ColorChanger();
}
void Start()
{
}
private void ColorChanger()
{
if (index <= 0)
{
DoorsLights(Color.grey);
}
else if (index == 1)
{
DoorsLights(Color.red);
}
else if (index == 2)
{
DoorsLights(Color.blue);
}
else if (index >= 3)
{
DoorsLights(Color.green);
}
}
private void DoorsLights(Color color)
{
myColor.color = color;
doorLight.color = color;
doorPLight.color = color;
}
}

编辑:

我工作得很好,我做了一个改变,而不是

index = EditorGUILayout.Popup(arrayLabel, script.index, script.options); 

我用了

index.intValue = EditorGUILayout.Popup(arrayLabel, script.index, script.options); 

如果要从自定义编辑器更新属性,则需要使用SerializedProperty。像这样:

[CustomEditor(typeof(DoorScript))]
public class ButtonDropDownMenu : Editor
{
SerializedProperty index;
void OnEnable()
{
index = serializedObject.FindProperty("index");
}
...

然后确保完成后您正在呼叫serializedObject.ApplyModifiedProperties();

public override void OnInspectorGUI()
{
base.OnInspectorGUI();
...
index = EditorGUILayout.Popup(arrayLabel, script.index, script.options);
...
serializedObject.ApplyModifiedProperties();
}

希望这能有所帮助!如果这不起作用,请告诉我

最新更新