Untiy中在Inspector面板中使用set/get

今天在尝试用脚本控制纹理图案的时候发现了一点小问题

c#的get/set写法是个很方便的东西,我也一直在用这种方式控制private成员的读取和写入,不过这种属性无法在Unity的inspector面板上显示,我以前是采取回避在Inspector写get/set的解决方法。不过这次尝试shader,如果不能在inspector修改参数,工作效率就很低了。于是先按照老办法,序列化试一下

[SerializeField] private int m_textureWidth = 512;

这么写之后,Inspector面板是有显示了,也能修改了,不过只要运行一下就能发现根本就没有调用到get/set而是直接对private属性进行了操作

查了一下文档,为了解决这个问题,Unity给出了一种继承类的解决方案


PropertyAttribute

class in UnityEngine

Description

Base class to derive custom property attributes from. Use this to create custom attributes for script variables.

A custom attributes can be hooked up with a custom PropertyDrawer class to control how a script variable with that attribute is shown in the Inspector.


于是我们可以先写一个custom class

public class SetPropertyAttribute : PropertyAttribute
{
	public string Name { get; private set; }
	public bool IsDirty { get; set; }

	public SetPropertyAttribute(string name)
	{
		this.Name = name;
	}
}

方法很简单,只有一个构造方法

然后在序列化的时候构造一个这样的类

    [SerializeField, SetPropertyAttribute("textureWidth")] private int m_textureWidth = 512;

然后就可以照常set/get了,改动Inspector面板也会调用到get/set

 public int textureWidth
    {
        get
        {
        }
        set
        {
        }
    }


参考:

http://www.xuanyusong.com/archives/3406

https://github.com/LMNRY/SetProperty

猜你喜欢

转载自blog.csdn.net/keven2148/article/details/79894683