I want to show a private variable from a script in the inspector, but I don’t want it to be serialized or allowed to be modified in the inspector. Is there a way to do this? I just want it to be readonly in the inspector. Currently I have to create a dummy public variable and assign the actual variable to it.
private int x;
public int dummyX;
void Update()
{
x++;
dummyX = x;
}
Thanks
If you change your inspector to debug mode you can see all private variables.
1 Like
Thanks. I didnt know about that until now.
If it can be serialized then it will be saved, and there’s no way to have something visible inside the default Inspector window without it being serialized, so you can’t separate the two.
You can make a field read only in the inspector with a small amount of work though. I’m not sure if there’s a better way than this since I’m still getting to grips with Unity, but this can be achieved by using a CustomPropertyDrawer and an attribute.
In ReadOnlyAttribute.cs:
using UnityEngine;
public class ReadOnlyAttribute : PropertyAttribute
{
}
In ReadOnlyPropertyDrawer.cs (make sure this is inside an Editor folder)
using UnityEngine;
using UnityEditor;
[CustomPropertyDrawer(typeof(ReadOnlyAttribute))]
public class ReadOnlyPropertyDrawer : PropertyDrawer
{
public override void OnGUI (Rect position, SerializedProperty property, GUIContent label)
{
bool wasEnabled = GUI.enabled;
GUI.enabled = false;
EditorGUI.PropertyField(position, property, label);
GUI.enabled = wasEnabled;
}
}
Then use like this:
[ReadOnly]
[SerializeField]
private bool useFixedUpdate = false;
2 Likes