Skip to content

Instantly share code, notes, and snippets.

@Petethegoat
Forked from antonkudin/RenameAttribute.cs
Created November 21, 2023 19:00
Show Gist options
  • Save Petethegoat/f1bb339451cb7b1a3134c7917f3e4b16 to your computer and use it in GitHub Desktop.
Save Petethegoat/f1bb339451cb7b1a3134c7917f3e4b16 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment