Unity3D研究院之Inspector視圖中的get/set使用(四)

轉(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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容