美文网首页
Unity 编辑器扩展十一 DecoratorDrawer

Unity 编辑器扩展十一 DecoratorDrawer

作者: 合肥黑 | 来源:发表于2021-12-12 09:49 被阅读0次

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 object
DrawerImageAttributeDrawer.GetHeight () (at Assets/Editor/DrawerImageAttributeDrawer.cs:25)

脚本先调用的是 GetHeight() 方法,因此当我们在 GetHeight() 方法中使用 _attribute.height 的时候便会报空指针的错误,因为此时的 _attribute 还没有初始化,因此让我们添加如下代码:

...
    private Texture2D image;
    private DrawerImageAttribute _attribute = new DrawerImageAttribute();
image.png

相关文章

网友评论

      本文标题:Unity 编辑器扩展十一 DecoratorDrawer

      本文链接:https://www.haomeiwen.com/subject/xgpltrtx.html