官术网_书友最值得收藏!

Variable visibility

One excellent feature of Unity specifically is that it exposes (shows) public class variables inside the Object Inspector in the Unity Editor, allowing you to edit and preview variables, even at runtime. This is especially convenient for debugging. However, by default, the Object Inspector doesn't expose private variables. They are typically hidden from the inspector. This isn't always a good thing because there are many cases where you'll want to debug or, at least, monitor private variables from the inspector without having to change their scope to public. There are two main ways to overcome this problem easily.

The first solution would be useful if you want to view all public and private variables in a class. You can toggle the Object Inspector in the Debug mode. To do this, click on the context menu icon in the top-right corner of the Inspector window and select Debug from the context menu, as shown in the following screenshot. When Debug is selected, all the public and private variables for a class will show.

Variable visibility

Enabling the Debug mode in the Object Inspector will show all the variables in a class

The second solution is useful for displaying specific private variables, variables that you mark explicitly as wanting to display in the Object Inspector. These will show in both the Normal and Debug modes. To achieve this, declare the private variable with the attribute [SerializeField]. C# attributes are considered later in this book, as shown here:

01 using UnityEngine;
02 using System.Collections;
03 
04 public class MyClass : MonoBehaviour 
05 {
06 //Will always show
07 public int PublicVar1;
08 
09 //Will always show
10 [SerializeField]
11 private int PrivateVar1;
12 
13 //Will show only in Debug Mode
14 private int PrivateVar2;
15 
16 //Will show only in Debug Mode
17 private int PrivateVar3;
18 }

Tip

You can also use the [HideInInspector] attribute to hide a global variable from the inspector.

主站蜘蛛池模板: 镇沅| 喀喇| 泰州市| 金川县| 新宾| 普宁市| 江门市| 广灵县| 岳西县| 商城县| 大邑县| 南华县| 镇原县| 武川县| 苏尼特左旗| 申扎县| 内丘县| 辽宁省| 洞口县| 崇左市| 彭山县| 綦江县| 肥乡县| 安福县| 张北县| 东乡县| 廊坊市| 府谷县| 利津县| 长春市| 顺平县| 无锡市| 隆子县| 新竹市| 商丘市| 天津市| 平顶山市| 海南省| 达日县| 临澧县| 泾源县|