Skip to content

Instantly share code, notes, and snippets.

@MattRix
Last active September 23, 2023 16:34
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save MattRix/9fb45606bfbc16254641e4d462117737 to your computer and use it in GitHub Desktop.
Save MattRix/9fb45606bfbc16254641e4d462117737 to your computer and use it in GitHub Desktop.
Read Only Attribute for Unity (just mark stuff as [ReadOnly] the same way you would use [HideInInspector])
using UnityEngine;
using System;
using System.Reflection;
using System.Text.RegularExpressions;
[AttributeUsage (AttributeTargets.Field,Inherited = true)]
public class ReadOnlyAttribute : PropertyAttribute {}
#if UNITY_EDITOR
[UnityEditor.CustomPropertyDrawer (typeof(ReadOnlyAttribute))]
public class ReadOnlyAttributeDrawer : UnityEditor.PropertyDrawer
{
public override void OnGUI(Rect rect, UnityEditor.SerializedProperty prop, GUIContent label)
{
bool wasEnabled = GUI.enabled;
GUI.enabled = false;
UnityEditor.EditorGUI.PropertyField(rect,prop);
GUI.enabled = wasEnabled;
}
}
#endif
@Flavelius
Copy link

Flavelius commented May 3, 2018

UnityEditor.EditorGUI.PropertyField(rect,prop, true); //to include children

@nico202
Copy link

nico202 commented Feb 18, 2019

Hi, what's the license of ReadOnlyAttribute.cs?
Can I use it in a BSD-3 clause project?

Thanks, Nicolò

@Yolo-Jerome
Copy link

Unfortunately it doesn't fully work for Lists:

[ReadOnly] public List<int> test = new List<int>(){ 1,2,3};

2019-04-02_1217

The most "dangerous" value to change is till available.


And it especially doesn't work for nested elements:

2019-04-02_1220

where the elements are of type

[Serializable]
public class TestClass
{
    public int num;
    public string text;
}

[ReadOnly] public List<TestClass> test = new List<TestClass>(){
    new TestClass(),
    new TestClass{num = 2, text = "Hi"},
    new TestClass{num = 3, text = "asd"}
};

also if it is not in a list like

[ReadOnly] public TestClass test = new TestClass();

@PlautoAbreu
Copy link

Unfortunately it doesn't fully work for Lists:

[ReadOnly] public List<int> test = new List<int>(){ 1,2,3};

2019-04-02_1217

The most "dangerous" value to change is till available.

And it especially doesn't work for nested elements:

2019-04-02_1220

where the elements are of type

[Serializable]
public class TestClass
{
    public int num;
    public string text;
}

[ReadOnly] public List<TestClass> test = new List<TestClass>(){
    new TestClass(),
    new TestClass{num = 2, text = "Hi"},
    new TestClass{num = 3, text = "asd"}
};

also if it is not in a list like

[ReadOnly] public TestClass test = new TestClass();

A few years later but I solved this issue by replacing

  • UnityEditor.EditorGUI.PropertyField(rect,prop);
    with:
  • EditorGUILayout.PropertyField(property, label, true);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment