在Unity Inspector中显示class变量

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

1. 变量是内置类型的,比如float, string, int, double类型的变量

2. 变量访问限制为public

例如如下脚本:

[csharp]  view plain  copy
  1. using UnityEngine;  
  2. using System.Collections;  
  3.   
  4. public class Test : MonoBehaviour  
  5. {  
  6.     public float f;  
  7.     // Use this for initialization  
  8.     void Start ()  
  9.     {  
  10.   
  11.     }  
  12.   
  13.     // Update is called once per frame  
  14.     void Update ()  
  15.     {  
  16.   
  17.     }  
  18. }  
在Inspector中显示为这样:


如果我们想要显示在Inspector中一个custom class 类型的变量呢?比如:

[csharp]  view plain  copy
  1. using UnityEngine;  
  2. using System.Collections;  
  3.   
  4. public class Test : MonoBehaviour  
  5. {  
  6.     public float f;  
  7.   
  8.     public Person person;  
  9.   
  10.     public class Person  
  11.     {  
  12.         public string name;  
  13.         public string address;  
  14.         public int age;  
  15.     }  
  16.     void Start ()  
  17.     {  
  18.   
  19.     }  
  20.   
  21.     // Update is called once per frame  
  22.     void Update ()  
  23.     {  
  24.   
  25.     }  
  26. }  

在Inspector中显示为:

可以看到,Person类型的变量并没有在Inspector中显示。为了显示person变量,我们可以采用下面的方法,在Person class类型声明前面加上[System.Serializable]

[csharp]  view plain  copy
  1. using UnityEngine;  
  2. using System.Collections;  
  3.   
  4. public class Test : MonoBehaviour  
  5. {  
  6.     public float f;  
  7.   
  8.     public Person person;  
  9.   
  10.     [System.Serializable]   
  11.     public class Person  
  12.     {  
  13.         public string name;  
  14.         public string address;  
  15.         public int age;  
  16.     }  
  17.     void Start ()  
  18.     {  
  19.   
  20.     }  
  21.   
  22.     // Update is called once per frame  
  23.     void Update ()  
  24.     {  
  25.   
  26.     }  
  27. }  

现在在Inspector视图中就能看到Person变量显示了:

Unity Inspector会默认显示脚本中的public变量,有时我们不想让这些变量显示,则可以在变量前面加上[HideInInspector],这样就能隐藏这个变量了。

[csharp]  view plain  copy
  1. using UnityEngine;  
  2. using System.Collections;  
  3.   
  4. public class Test : MonoBehaviour  
  5. {  
  6.     [HideInInspector]  
  7.     public float f;  
  8.   
  9.     public Person person;  
  10.   
  11.     [System.Serializable]   
  12.     public class Person  
  13.     {  
  14.         public string name;  
  15.         public string address;  
  16.         public int age;  
  17.     }  
  18.     void Start ()  
  19.     {  
  20.   
  21.     }  
  22.   
  23.     // Update is called once per frame  
  24.     void Update ()  
  25.     {  
  26.   
  27.     }  
  28. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值