Last active
December 27, 2021 06:50
-
-
Save SiarheiPilat/0f3fd9a16ff5dc876a834e5205776018 to your computer and use it in GitHub Desktop.
Custom attribute that adds a button in front of a variable in the Inspector, pressing which performs an attempt to fill in the object reference with corresponding object that is sitting on the inspected game object.
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
using UnityEngine; | |
using UnityEditor; | |
// REMEMBER that for custom attributes with property drawers, the attribute script should be in normal folder, while the drawer script - in the editor folder | |
public class AutofillAttribute : PropertyAttribute { } | |
[CustomPropertyDrawer(typeof(AutofillAttribute))] | |
public class AutofillAttributeDrawer : PropertyDrawer | |
{ | |
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) | |
{ | |
if (GUI.Button(new Rect(position.x, position.y, 50f, 15f), "Fill")) | |
{ | |
string type = property.type.Replace("PPtr<$", "").Replace(">", ""); | |
property.objectReferenceValue = (Selection.activeObject as GameObject).GetComponent(type); | |
if (type == "GameObject") property.objectReferenceValue = (Selection.activeObject as GameObject).gameObject; | |
} | |
EditorGUI.PropertyField(new Rect(position.x + 51f, position.y, position.width - 51f, position.height), property, label, true); | |
} | |
public override float GetPropertyHeight(SerializedProperty property, GUIContent label) | |
{ | |
return EditorGUI.GetPropertyHeight(property); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment