Book Image

Mastering Unity Scripting

By : Alan Thorn
Book Image

Mastering Unity Scripting

By: Alan Thorn

Overview of this book

Table of Contents (17 chapters)
Mastering Unity Scripting
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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.

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.