您的位置:首页 > 移动开发 > Unity3D

在Unity Inspector中显示class变量

2016-12-16 11:59 435 查看
通过Unity Inspector,我们能够很方便的给脚本中变量赋值。变量要在Inspector中显示,需要满足下面两个条件:

1. 变量是内置类型的,比如float, string, int, double类型的变量
2. 变量访问限制为public
例如如下脚本:

[csharp] view
plain copy

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 类型的变量呢?比如:

[csharp] view
plain copy

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]

[csharp] view
plain copy

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],这样就能隐藏这个变量了。

[csharp] view
plain copy

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

    {  

  

    }  

}  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  unity c#