在Unity Inspector中显示class变量

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

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

	}
}



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值