class unity 定义类_[Unity]用PropertyDrawer自定义struct/class的外观

一般来说,当我们要扩展编辑器时,我们会从Editor类继承,为自己的MonoBehaviour实现不同的外观。

但是如果有一个struct/class,在许多地方被使用,Unity默认的外观又不够好看,此时想修改它的外观,就需要使用PropertyDrawer了。

上图是一个Monobehaviour中包含一个简单的struct(TileCoord类),包含两个int,但是显示效果十分别扭。

实现对应的PropertyDrawer后

相对于Editor类可以修改MonoBehaviour的外观,我们可以简单的理解PropertyDrawer为修改struct/class的外观的Editor类。

实现上面的效果的代码如下

[CustomPropertyDrawer(typeof(TileCoord))]

public class TileCoordEditor : PropertyDrawer {

public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) {

var x = property.FindPropertyRelative("x");

var y = property.FindPropertyRelative("y");

float LabelWidth = EditorGUIUtility.labelWidth;

var labelRect = new Rect(position.x, position.y, LabelWidth, position.height);

var xRect = new Rect(position.x + LabelWidth, position.y, (position.width - LabelWidth) / 2 - 20, position.height);

var yRect = new Rect(position.x + LabelWidth + (position.width - LabelWidth) / 2 - 20 , position.y, (position.widt

你可能感兴趣的:(class,unity,定义类)