Unity 编辑器扩展十一 DecoratorDrawer
Unity Editor 基础篇(八):Decorator DrawersUnity Editor 实践 : 自定义小工具
一、示例
在Scripts文件夹下添加
using System.Collections;using System.Collections.Generic;using UnityEngine;public class DrawerImageAttribute : PropertyAttribute{ public DrawerImageAttribute() { }}//using System.Collections;using System.Collections.Generic;using UnityEngine;public class TestImageAttribute : MonoBehaviour{ public float ff;}
在Editor文件夹下添加
using System.Collections;using System.Collections.Generic;using UnityEngine;using UnityEditor;public class DrawerImageAttributeDrawer : DecoratorDrawer{ private Texture2D image; public override void OnGUI(Rect position) { Debug.Log("DrawerImageAttributeDrawer OnGUI"); if (image == null) { image = Resources.Load<Texture2D>("gold"); } GUI.DrawTexture(position, image); } public override float GetHeight() { return base.GetHeight(); }}
如下图,金币图绘制产生变形,需要修改GetHeight() 方法
image.png
2.
using System.Collections;using System.Collections.Generic;using UnityEngine;public class DrawerImageAttribute : PropertyAttribute{ public int height; public DrawerImageAttribute() { } public DrawerImageAttribute(int _height) { height = _height; }}using System.Collections;using System.Collections.Generic;using UnityEngine;using UnityEditor;public class DrawerImageAttributeDrawer : DecoratorDrawer{ private Texture2D image; private DrawerImageAttribute _attribute; public override void OnGUI(Rect position) { Debug.Log("DrawerImageAttributeDrawer OnGUI"); if (image == null) { image = Resources.Load<Texture2D>("gold"); } _attribute = (DrawerImageAttribute)attribute; GUI.DrawTexture(position, image); } public override float GetHeight() { return base.GetHeight() + _attribute.height; }}public class TestImageAttribute : MonoBehaviour{ public float ff;}
报错了:
NullReferenceException: Object reference not set to an instance of an objectDrawerImageAttributeDrawer.GetHeight () (at Assets/Editor/DrawerImageAttributeDrawer.cs:25)
脚本先调用的是 GetHeight() 方法,因此当我们在 GetHeight() 方法中使用 _attribute.height 的时候便会报空指针的错误,因为此时的 _attribute 还没有初始化,因此让我们添加如下代码:
... private Texture2D image; private DrawerImageAttribute _attribute = new DrawerImageAttribute();
image.png
页:
[1]