Making a Variable Read-Only in the Unity Inspector

Unity Inspector Customization

Making a Variable Read-Only in the Unity Inspector

 Hello friends, today I will explain how you can make variables defined as Public and SerializeField in Unity uneditable from the Inspector window. The image just below will help you better understand what we will do.

Unity Read Only Variable

As you can see in the screenshot above, the last two variables cannot be edited in Unity. Now let's see how we did it.

We need two Scripts for this process, you can name them as you wish, but these are the names I generally use for this operation.

  • 1. My Script is called ReadOnlyEditor
  • 2. My Script is called ReadOnlyValue
We need to put the first of these into a folder named "Editor", otherwise you will encounter errors when building your game in Unity. You should always put scripts containing Editor modifications in a folder named "Editor".

Now let's move on to our codes


ReadOnlyEditor Script Code

// We include our libraries
using UnityEngine;
using UnityEditor;

[CustomPropertyDrawer(typeof(ReadOnlyValue))] // We specify that it draws a custom value and that custom value's type is ReadOnlyValue.
public class ReadOnlyEditor : PropertyDrawer // We derive our class from the PropertyDrawer class
{
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) // Overrides to the GUI and gets the values
    {
        GUI.enabled = false; // We disable the GUI
        EditorGUI.PropertyField(position, property, label, true); // We provide the desired properties
        GUI.enabled = true; // We enable the GUI again
    }
}

ReadOnlyValue Script Code

The name we give our class here actually changes how we call this feature in the usage section below.
// We include our library
using UnityEngine;
public class ReadOnlyValue : PropertyAttribute { } // We created an empty class and indicated that this class is an Editor Attribute, i.e. editor modifier, and derived from that class.

Usage

Yes friends, after we have written our code correctly, all we have to do to use it is to write "[ReadOnlyValue]" before the variable we want to use.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Example : MonoBehaviour
{
    // Editable Variables
    public float test;
    [SerializeField] private float test1;

    // Variables not editable from the Inspector window
    [ReadOnlyValue]public float test2;
    [SerializeField] [ReadOnlyValue] private float test3;
}

If you want to download the version I wrote and other plugins/packages I wrote, you can use the links below.

My Unity Packages (Github)

Unity Read Only Variable (Github)