轉(zhuǎn)載自:http://www.xuanyusong.com/archives/3406
get set 使用起來很方便,但是編輯時(shí)在Inspector視圖中問題就來了,因?yàn)間et/set的屬性即使是public了,但是在Inspector視圖中依然不顯示。。谷歌一下估計(jì)就是下面這樣的答案。
C#
publicintwidth
{
get{
return_width;
}
set{
_width=value;
}
}
[SerializeField]
privateint_width;
如下圖所示問題又來了,因?yàn)樵诰庉嬆J较滦薷腤idth的值,但是代碼中的 set 壓根就沒執(zhí)行。。
先看看[SerializeField]的含義,它用來序列化一個(gè)區(qū)域,通俗的來說[SerializeField]可以讓private 的屬性在Inspector視圖中顯示出來。。
那么上面的set沒執(zhí)行的原因就出來了,因?yàn)槲覀兏牡氖莗rivate _width并不是 public width。由此可見此段代碼在編輯模式下是毫無用處的。。
我偏偏就想在編輯時(shí)響應(yīng) set 的操作怎么辦?我想做的是在set里面加一個(gè)自己寫的方法。
TestInspector.cs放在Editor目錄下
C#
usingUnityEngine;
usingUnityEditor;
usingSystem.Collections.Generic;
[CustomEditor(typeof(Test))]
publicclassTestInspector:Editor{
Test model;
publicoverridevoidOnInspectorGUI(){
model=target asTest;
intwidth=EditorGUILayout.IntField("Width",model.width);
if(model.width!=width){
model.width=width;
}
base.DrawDefaultInspector();
}
}
Test掛在任意游戲?qū)ο笊稀?br> C#
usingUnityEngine;
usingSystem.Collections;
publicclassTest:MonoBehaviour
{
publicintwidth
{
get{
return_width;
}
set{
Debug.Log("set :"+value);
_width=value;
}
}
privateint_width;
}
如下圖所示,在編輯模式下用鼠標(biāo)修改width的值。 log輸出了說明 get set 已經(jīng)響應(yīng)了。
感謝下面好友的留言,另外一種實(shí)現(xiàn)的方式,我試了一下也很好用。
https://github.com/LMNRY/SetProperty