Skip to content

Instantly share code, notes, and snippets.

@antonkudin
Created November 21, 2023 02:49
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save antonkudin/3b4bcd3e665b09192f7705fe32867a2b to your computer and use it in GitHub Desktop.
Save antonkudin/3b4bcd3e665b09192f7705fe32867a2b to your computer and use it in GitHub Desktop.
Rename variable names inside your properties
using UnityEngine;
#if UNITY_EDITOR
[System.AttributeUsage(System.AttributeTargets.Field)]
public class RenameAttribute : PropertyAttribute
{
public string[] renamePairs;
public RenameAttribute(params string[] renamePairs)
{
this.renamePairs = renamePairs;
}
}
#endif
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
[CustomPropertyDrawer(typeof(RenameAttribute))]
public class RenameDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
EditorGUI.BeginProperty(position, label, property);
// SerializedProperty isExpanded = property.FindPropertyRelative("isExpanded");
property.isExpanded = EditorGUI.Foldout(new Rect(position.x, position.y, position.width, EditorGUIUtility.singleLineHeight), property.isExpanded, label.text, true);
EditorGUI.indentLevel++;
if (property.isExpanded)
{
RenameAttribute renameAttribute = attribute as RenameAttribute;
foreach (string renamePair in renameAttribute.renamePairs)
{
string[] pair = renamePair.Split('=');
if (pair.Length==2) {
string originalName = pair[0].Trim();
string newName = pair[1].Trim();
SerializedProperty targetProperty = property.FindPropertyRelative(originalName);
if (targetProperty != null) {
var height = EditorGUI.GetPropertyHeight(targetProperty);
EditorGUI.PropertyField(new Rect(position.x, position.y + EditorGUIUtility.singleLineHeight, position.width, height), targetProperty, new GUIContent(newName));
position.y += height;
}
}else
{
Debug.LogError("Rename attribute format is incorrect. Should be \"originalName = newName\" not "+renamePair);
}
}
}
EditorGUI.indentLevel--;
EditorGUI.EndProperty();
}
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
if (property.isExpanded){
RenameAttribute renameAttribute = attribute as RenameAttribute;
float height = 0;
foreach (string renamePair in renameAttribute.renamePairs)
{
string[] pair = renamePair.Split('=');
if (pair.Length==2) {
string originalName = pair[0].Trim();
SerializedProperty targetProperty = property.FindPropertyRelative(originalName);
if (targetProperty != null)
height += EditorGUI.GetPropertyHeight(targetProperty);
}
}
return EditorGUIUtility.singleLineHeight + height;
}else
return EditorGUIUtility.singleLineHeight;
}
}
#endif
@antonkudin
Copy link
Author

image

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