在Unity中使用属性Property
C#中的属性Property
属性,即set、get访问器,一般起到过滤异常值或者在字段赋值时执行某些操作的作用。如下代码描述了一个私有字段_pointSize和其属性pointSize。
private float _pointSize = 0.05f;
public float pointSize {
set { _pointSize = value;
_pointSize = Mathf.Max(0, _pointSize);
_pointSize = Mathf.Min(0.02f, _pointSize);
material.SetFloat("_PointSize", _pointSize);
}
get { return _pointSize; }
}
问题的出现
想实现的功能是,在对pointSize赋值的同时对值进行过滤,并且同时修改某材质的shader参数。
目前来说,如果是在代码中修改pointSize值的话,是可以实现功能的,但是同时为了方便调试,又希望可以在Inspector中修改参数的时候生效。
但是,私有字段_pointSize在Inspector中是不显示的,为使其显示,可在上方添加:
[SerializeField]
这样虽然可以显示,但显示的只是私有字段_pointSize,在Inspector修改其值的时候并不会执行set访问器里的代码。
问题的解决
经查阅资料,可通过添加SetProperty插件解决:
插件下载
- 网址:https://github.com/LMNRY/SetProperty
- 点击Code-Download ZIP下载压缩包
插件使用
-
在unity中新建一SetProperty (任意名字皆可)文件夹
-
将解压得到的所有文件拷贝入新建的文件夹
-
使用SetProperty 属性说明实现功能:在代码前添加SetProperty 属性说明,即可实现在Inspector中访问属性
[SerializeField, SetProperty("pointSize")]//如果要显示私有字段或属性,需要加上这个
private float _pointSize = 0.05f;
public float pointSize {
set { _pointSize = value;
_pointSize = Mathf.Max(0, _pointSize);
_pointSize = Mathf.Min(0.02f, _pointSize);
material.SetFloat("_PointSize", _pointSize);
}
get { return _pointSize; }
}
原理
好像原理挺简单,但鄙人颇懒,不看。