找回密码
 立即注册
查看: 499|回复: 0

Unity 编辑器扩展十一 DecoratorDrawer

[复制链接]
发表于 2021-12-14 21:18 | 显示全部楼层 |阅读模式
Unity Editor 基础篇(八):Decorator Drawers
Unity 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{    [DrawerImage]    public float ff;}
在Editor文件夹下添加
using System.Collections;using System.Collections.Generic;using UnityEngine;using UnityEditor;[CustomPropertyDrawer(typeof(DrawerImageAttribute))]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;[CustomPropertyDrawer(typeof(DrawerImageAttribute))]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{    [DrawerImage(150)]    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

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Unity开发者联盟 ( 粤ICP备20003399号 )

GMT+8, 2024-9-23 01:21 , Processed in 0.106384 second(s), 26 queries .

Powered by Discuz! X3.5 Licensed

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表