Skip to content

Instantly share code, notes, and snippets.

@unitycoder
Created January 10, 2023 09:51
Show Gist options
  • Select an option

  • Save unitycoder/30e2e75794d111dbbbb5313fe8633c44 to your computer and use it in GitHub Desktop.

Select an option

Save unitycoder/30e2e75794d111dbbbb5313fe8633c44 to your computer and use it in GitHub Desktop.
unity how to make inspector property drawer for custom interface?
// chatGPT
// in Unity, you can create a custom property drawer for a class or interface by creating a script that inherits from UnityEditor.PropertyDrawer and overriding the OnGUI() method. In the OnGUI() method, you can write the custom code to handle drawing the interface fields in the Unity inspector.
// Here's an example of a property drawer for a custom interface called ICustomInterface:
// Make sure this script is in a folder named "Editor" so Unity recognize it as an Editor script.
using UnityEditor;
using UnityEngine;
[CustomPropertyDrawer(typeof(ICustomInterface))]
public class CustomInterfaceDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
// Get the object that implements the ICustomInterface
ICustomInterface customInterface = (ICustomInterface)fieldInfo.GetValue(property.serializedObject.targetObject);
// Draw the custom fields for the interface
customInterface.DrawInspector();
}
}
// Then, in the class or struct that implements ICustomInterface, define a method DrawInspector that will handle the actual drawing of the interface fields.
public class MyClass : MonoBehaviour, ICustomInterface
{
public void DrawInspector()
{
// Draw your interface fields here
EditorGUILayout.LabelField("My Label");
EditorGUILayout.IntField("My Int", myInt);
// etc
}
}
// Now, when you select an object in the Unity editor that has a component that implements ICustomInterface, the custom interface fields will be drawn in the inspector using the custom property drawer.
// // Additionally, You could also specify the height of your custom property drawer with GetPropertyHeight(SerializedProperty property, GUIContent label)
public override float GetPropertyHeight(SerializedProperty property, GUIContent label) {
// return the height of your property drawer here
return 30f;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment