通过Unity Inspector,我们能够很方便的给脚本中变量赋值。变量要在Inspector中显示,需要满足下面两个条件:
在Inspector中显示为:
现在在Inspector视图中就能看到Person变量显示了:
1. 变量是内置类型的,比如float, string, int, double类型的变量
2. 变量访问限制为public
例如如下脚本:
using UnityEngine;
using System.Collections;
public class Test : MonoBehaviour
{
public float f;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
}
}
在Inspector中显示为这样:
如果我们想要显示在Inspector中一个custom class 类型的变量呢?比如:
using UnityEngine;
using System.Collections;
public class Test : MonoBehaviour
{
public float f;
public Person person;
public class Person
{
public string name;
public string address;
public int age;
}
void Start ()
{
}
// Update is called once per frame
void Update ()
{
}
}
在Inspector中显示为:
可以看到,Person类型的变量并没有在Inspector中显示。为了显示person变量,我们可以采用下面的方法,在Person class类型声明前面加上[System.Serializable]:
using UnityEngine;
using System.Collections;
public class Test : MonoBehaviour
{
public float f;
public Person person;
[System.Serializable]
public class Person
{
public string name;
public string address;
public int age;
}
void Start ()
{
}
// Update is called once per frame
void Update ()
{
}
}
现在在Inspector视图中就能看到Person变量显示了:
Unity Inspector会默认显示脚本中的public变量,有时我们不想让这些变量显示,则可以在变量前面加上[HideInInspector],这样就能隐藏这个变量了。
using UnityEngine;
using System.Collections;
public class Test : MonoBehaviour
{
[HideInInspector]
public float f;
public Person person;
[System.Serializable]
public class Person
{
public string name;
public string address;
public int age;
}
void Start ()
{
}
// Update is called once per frame
void Update ()
{
}
}