Last active
April 23, 2018 16:29
-
-
Save Hyrtwol/c427be43e187c6eae8dd11b80edbc445 to your computer and use it in GitHub Desktop.
Unity scraps
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// show the field as a read only label (runtime script) | |
[AttributeUsage(AttributeTargets.Field)] | |
public class ReadOnlyAttribute : PropertyAttribute { } | |
// read only drawer (editor script) | |
[CustomPropertyDrawer(typeof (ReadOnlyAttribute))] | |
public class ReadOnlyAttributeDrawer : PropertyDrawer | |
{ | |
private static readonly GUIStyle Style = EditorStyles.label; | |
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) | |
{ | |
switch (property.propertyType) | |
{ | |
case SerializedPropertyType.Integer: | |
EditorGUI.IntField(position, label, property.intValue, Style); | |
break; | |
case SerializedPropertyType.Float: | |
EditorGUI.FloatField(position, label, property.floatValue, Style); | |
break; | |
case SerializedPropertyType.String: | |
EditorGUI.TextField(position, label, property.stringValue, Style); | |
break; | |
default: | |
EditorGUI.LabelField(position, "The property type is not valid " + property.propertyType + " for ReadOnlyAttribute to work!"); | |
break; | |
} | |
} | |
} | |
// render layer dropdown (runtime script) | |
[AttributeUsage(AttributeTargets.Field)] | |
public class LayerAttribute : PropertyAttribute { } | |
// layer drawer (editor script) | |
[CustomPropertyDrawer(typeof (LayerAttribute))] | |
public class LayerAttributeDrawer : PropertyDrawer | |
{ | |
private const SerializedPropertyType ValidPropertyType = SerializedPropertyType.Integer; | |
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) | |
{ | |
if (property.propertyType != ValidPropertyType) | |
{ | |
EditorGUI.LabelField(position, "The property has to be a " + ValidPropertyType + " for LayerAttribute to work!"); | |
return; | |
} | |
property.intValue = EditorGUI.LayerField(position, label, property.intValue); | |
} | |
} | |
public class Example : MonoBehaviour | |
{ | |
[Range(1f, 10f)] | |
public float CamreaScale = 2f; | |
[Layer] | |
public int RenderLayer = 10; // see project settings, tags & layers | |
[ReadOnly] | |
public float TraceDistance; // the value is still saved by unity so not optimal | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment