Version: 2018.2 (switch to 2018.3b or 2017.4)
Creating and Using Scripts
Controlling GameObjects using components
Other Versions

Variables and the Inspector

When creating a script, you are essentially creating your own new type of componentA functional part of a GameObject. A GameObject can contain any number of components. Unity has many built-in components, and you can create your own by writing scripts that inherit from MonoBehaviour. More info
See in Glossary
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, alowing 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”.

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#, you must declare a variable as public to see it 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.

Did you find this page useful? Please give it a rating:

Creating and Using Scripts
Controlling GameObjects using components