Using attributes and modifying the Inspector

As you create your games, there will be times when you will want to control some parameters at run-time to perform tests. For example: you may want to be able to modify a variable inside the Inspector while the game is running by typing its value or by using a slider to make this easier. In both cases, you will need to modify the Inspector and the way data is presented within.

Thankfully, Unity makes it possible for you to perform these changes from your own C# script. The first thing we could do, is to make our variable public, as all public variables are available and modifiable in the Inspector.

We could also, in addition, define a range, so that we know that people testing the game within Unity can only modify the values of this variable within a specific range, as illustrated in the following code.


public float myVariable;

In the previous code, we use the keyword Range followed by values that indicate the range for the variable myVariable.

Next, we could make it possible to display and change the value of private variables. By default, private variables are not displayed in the Inspector, unless they are proceeded by using the attribute SerializedField as illustrated in the next code.


private int myPrivateVariable;


This being said, Unity also makes it possible to use attributes to modify the behaviours of variables, classes, or methods, when the scene is not played. For example, the following attributes can be used at run-time:

  • HideInInspector: can be used to hide some variables in the Inspector; for example, a variable might be public but you may not want to make it possible to readjust its value in the Inspector.
public class TestSerialized : MonoBehaviour



    public int myPrivateVariable;//this variable will be hidden

     public Vector3 test;


  • Serializable: this attribute gives the opportunity to serialize a class, so that member variables content can be displayed in the Inspector.

public class TestSerialized : MonoBehaviour


// All public member variables will be visible in the Inspector

     public int myPrivateVariable;

     public Vector3 test;


ExecuteInEditMode: this attribute makes it possible to execute a script even in edit mode. Please use this attribute carefully as any of the changes made will be permanent in this case. When things are changed at run-time, your scene will be back to normal when your stop playing it; however, when you perform actions from your code that is executed in edit mode (i.e., with the attribute ExecuteInEditMode) you may need to be careful as the changes made from your script will be permanent.

Related Articles:

Leave a Reply

Your email address will not be published. Required fields are marked *