在Unity Inspector中顯示class變數
阿新 • • 發佈:2019-02-04
通過Unity Inspector,我們能夠很方便的給指令碼中變數賦值。變數要在Inspector中顯示,需要滿足下面兩個條件:
在Inspector中顯示為: :
現在在Inspector檢視中就能看到Person變數顯示了:
1. 變數是內建型別的,比如float, string, int, double型別的變數
2. 變數訪問限制為public
例如如下指令碼:
- using UnityEngine;
- using System.Collections;
- publicclass Test : MonoBehaviour
- {
- publicfloat f;
- // Use this for initialization
-
void Start ()
- {
- }
- // Update is called once per frame
- void Update ()
- {
- }
- }
如果我們想要顯示在Inspector中一個custom class 型別的變數呢?比如:
- using UnityEngine;
- using System.Collections;
- publicclass Test : MonoBehaviour
- {
- publicfloat f;
-
public Person person;
- publicclass Person
- {
- publicstring name;
- publicstring address;
- publicint age;
- }
- void Start ()
- {
- }
- // Update is called once per frame
- void Update ()
- {
- }
- }
在Inspector中顯示為:
可以看到,Person型別的變數並沒有在Inspector中顯示。為了顯示person變數,我們可以採用下面的方法,在Person class型別宣告前面加上[System.Serializable]
- using UnityEngine;
- using System.Collections;
- publicclass Test : MonoBehaviour
- {
- publicfloat f;
- public Person person;
- [System.Serializable]
- publicclass Person
- {
- publicstring name;
- publicstring address;
- publicint age;
- }
- void Start ()
- {
- }
- // Update is called once per frame
- void Update ()
- {
- }
- }
現在在Inspector檢視中就能看到Person變數顯示了:
Unity Inspector會預設顯示指令碼中的public變數,有時我們不想讓這些變數顯示,則可以在變數前面加上[HideInInspector],這樣就能隱藏這個變量了。
- using UnityEngine;
- using System.Collections;
- publicclass Test : MonoBehaviour
- {
- [HideInInspector]
- publicfloat f;
- public Person person;
- [System.Serializable]
- publicclass Person
- {
- publicstring name;
- publicstring address;
- publicint age;
- }
- void Start ()
- {
- }
- // Update is called once per frame
- void Update ()
- {
- }
- }