Skip to content

Instantly share code, notes, and snippets.

@nevarman
Last active February 28, 2017 15:18
Show Gist options
  • Save nevarman/51e23d5783abbaa763a31cd7755d9214 to your computer and use it in GitHub Desktop.
Save nevarman/51e23d5783abbaa763a31cd7755d9214 to your computer and use it in GitHub Desktop.
Makes your private or protected serialized fields non editable from Unity editor
using System;
using UnityEngine;
using System.Collections;
[AttributeUsage(AttributeTargets.Field)]
public class ReadOnlySerializeFieldAttribute : PropertyAttribute
{
public ReadOnlySerializeFieldAttribute()
{ }
}
#if UNITY_EDITOR
using UnityEditor;
[CustomPropertyDrawer(typeof(ReadOnlySerializeFieldAttribute))]
public class ReadOnlySerializeFieldDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
var value = GetPropertyValue(property);
var propertyName = property.displayName;
EditorGUI.LabelField(position, string.Format("{0}: {1}", propertyName, value), EditorStyles.boldLabel);
}
public static object GetPropertyValue(SerializedProperty prop)
{
if (prop == null)
throw new System.ArgumentNullException("prop");
switch (prop.propertyType)
{
case SerializedPropertyType.Integer:
return prop.intValue;
case SerializedPropertyType.Boolean:
return prop.boolValue;
case SerializedPropertyType.Float:
return prop.floatValue;
case SerializedPropertyType.String:
return prop.stringValue;
case SerializedPropertyType.Color:
return prop.colorValue;
case SerializedPropertyType.ObjectReference:
return prop.objectReferenceValue;
case SerializedPropertyType.LayerMask:
return (LayerMask)prop.intValue;
case SerializedPropertyType.Enum:
return prop.enumValueIndex;
case SerializedPropertyType.Vector2:
return prop.vector2Value;
case SerializedPropertyType.Vector3:
return prop.vector3Value;
case SerializedPropertyType.Vector4:
return prop.vector4Value;
case SerializedPropertyType.Rect:
return prop.rectValue;
case SerializedPropertyType.ArraySize:
return prop.arraySize;
case SerializedPropertyType.Character:
return (char)prop.intValue;
case SerializedPropertyType.AnimationCurve:
return prop.animationCurveValue;
case SerializedPropertyType.Bounds:
return prop.boundsValue;
default:
return "Can not handle this types.";
}
}
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment