readonly
使它们也 non-serialized
,即不会在检查器中显示。
请注意,PropertyDrawer
不仅限于 class
类型,还可用于 struct
类型。
实际上并不需要一个 CustomPropertyDrawer
。
您可以使用公共的只读属性来访问私有字段,并使用[SerializeField]
将其显示在检查器中。这使它们仅可通过检查器进行编辑,而无法通过其他类进行编辑。
[Serializable]
public struct HexPoint : IEquatable<HexPoint>
{
public int x { get { return _x; } }
public int y { get { return _y; } }
public int z { get { return _z; } }
[SerializeField] private int _x;
[SerializeField] private int _y;
[SerializeField] private int _z;
public bool Equals(HexPoint other)
{
return _x == other._x && _y == other._y && _z == other._z;
}
public override bool Equals(object obj)
{
return obj is HexPoint other && Equals(other);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = _x;
hashCode = (hashCode * 397) ^ _y;
hashCode = (hashCode * 397) ^ _z;
return hashCode;
}
}
}
如果你真的想使用PropertyDrawer
,除了在检查器中禁止编辑这些值并保存和查看它们之外,还可以添加如下代码:
[Serializable]
public struct HexPoint : IEquatable<HexPoint>
{
public int x { get { return _x; } }
public int y { get { return _y; } }
public int z { get { return _z; } }
[SerializeField] private int _x;
[SerializeField] private int _y;
[SerializeField] private int _z;
public bool Equals(HexPoint other)
{
return _x == other._x && _y == other._y && _z == other._z;
}
public override bool Equals(object obj)
{
return obj is HexPoint other && Equals(other);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = _x;
hashCode = (hashCode * 397) ^ _y;
hashCode = (hashCode * 397) ^ _z;
return hashCode;
}
}
#if UNITY_EDITOR
[CustomPropertyDrawer(typeof(HexPoint))]
public class HexPointDrawer : PropertyDrawer
{
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
return EditorGUIUtility.singleLineHeight * (EditorGUIUtility.wideMode ? 1 : 2);
}
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
var x = property.FindPropertyRelative(nameof(_x));
var y = property.FindPropertyRelative(nameof(_y));
var z = property.FindPropertyRelative(nameof(_z));
EditorGUI.BeginProperty(position, label, property);
{
EditorGUI.BeginDisabledGroup(true);
{
EditorGUI.Vector3IntField(position, label, new Vector3Int(x.intValue, y.intValue, z.intValue));
}
EditorGUI.EndDisabledGroup();
}
EditorGUI.EndProperty();
}
}
#endif
}
提示:在更改后检查值的方法,MonoBehaviour.OnValidate 可能对您有帮助。
PropertyDrawer
,可以额外完成这个任务。 - derHugo