Version: 2019.4
Creating and Using Scripts
Instantiating Prefabs at run time

Variables and the Inspector

When creating a script, you are essentially creating your own new type of component that can be attached to Game Objects just like any other component.

Just like other Components often have properties that are editable in the inspector, you can allow values in your script to be edited from the InspectorA Unity window that displays information about the currently selected GameObject, asset or project settings, allowing you to inspect and edit the values. More info
See in Glossary
too.

using UnityEngine;
using System.Collections;

public class MainPlayer : MonoBehaviour 
{
    public string myName;
    
    // Use this for initialization
    void Start () 
    {
        Debug.Log("I am alive and my name is " + myName);
    }
}

This code creates an editable field in the Inspector labelled “My Name”.

The Inspector might display variable names differently to how you define them in a script if the name conforms to one of a set of rules:

  • Removes “m_” from the beginning
  • Removes “k” from the beginning
  • Removes “_” from the beginning
  • Capitalizes the first letter
  • Adds a space between lowercase and uppercase characters
  • Adds a space between an acronym and an uppercase character at the beginning of the next word

There are some special cases, such as “iPad” or “x64”, where these rules are not applied.

Unity creates the Inspector label by introducing a space wherever a capital letter occurs in the variable name. However, this is purely for display purposes and you should always use the variable name within your code. If you edit the name and then press Play, you will see that the message includes the text you entered.

In C#, the simplest way to see a variable in the Inspector is to declare it as public. An alternative method is to use SerializeField. Conversely, you can use HideInInspector to prevent a public variable from being displayed in the Inspector.

Unity will actually let you change the value of a script’s variables while the game is running. This is very useful for seeing the effects of changes directly without having to stop and restart. When gameplay ends, the values of the variables will be reset to whatever they were before you pressed Play. This ensures that you are free to tweak your object’s settings without fear of doing any permanent damage.

Creating and Using Scripts
Instantiating Prefabs at run time