我想创建一个ProbeManager
,可以在其中使用Handles
在探针之间移动。这是我的MonoBehaviour
及其Custom Editor
:
MonoBehaviour:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[ExecuteInEditMode]
public class ProbeManager : MonoBehaviour
{
public Probe[] probes;
[System.Serializable]
public class Probe
{
public Vector3 pos;
public float radius;
}
void OnDrawGizmosSelected()
{
Gizmos.color = Color.white;
for (int i = 0; i < probes.Length; i++)
{
Probe probe = probes[i];
Gizmos.DrawWireSphere(probe.pos, probe.radius);
}
}
}
自定义编辑器:
using UnityEngine;
using UnityEditor;
using System;
[CustomEditor(typeof(ProbeManager))]
public class ProbeManagerEditor : Editor
{
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
}
protected virtual void OnSceneGUI()
{
ProbeManager probe_manager = (ProbeManager)target;
EditorGUI.BeginChangeCheck();
for (int i = 0; i < probe_manager.probes.Length; i++)
{
probe_manager.probes[i].pos = Handles.PositionHandle(probe_manager.probes[i].pos, Quaternion.identity);
}
EditorGUI.EndChangeCheck();
}
}
问题是,当我通过 Inspector 更改探针的属性radius
或position
时,它可以正常工作。但是,当我尝试用手柄将它们移到旁边时,在我按Play
之后,它们会传回其先前的位置。
我怀疑它与序列化有关,但这就是:(
答案 0 :(得分:0)
我应该通过serializedObject
完成此操作:
using UnityEngine;
using UnityEditor;
using System;
[CustomEditor(typeof(ProbeManager))]
public class ProbeManagerEditor : Editor
{
SerializedProperty probes_prop;
private void OnEnable()
{
probes_prop = serializedObject.FindProperty("probes");
}
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
}
protected virtual void OnSceneGUI()
{
ProbeManager probe_manager = (ProbeManager)target;
for (int i = 0; i < probe_manager.probes.Length; i++)
{
EditorGUI.BeginChangeCheck();
Vector3 position = Handles.PositionHandle(probe_manager.probes[i].pos, Quaternion.identity);
SerializedProperty probe = probes_prop.GetArrayElementAtIndex(i);
SerializedProperty probe_pos = probe.FindPropertyRelative("pos");
if (EditorGUI.EndChangeCheck() == true)
{
probe_pos.vector3Value = position;
serializedObject.ApplyModifiedProperties();
}
}
}
}