Skip to content

Instantly share code, notes, and snippets.

@AnsisMalins
Created September 27, 2020 20:47
Show Gist options
  • Save AnsisMalins/f713eee91baa5ad6eb2af8b1f284586d to your computer and use it in GitHub Desktop.
Save AnsisMalins/f713eee91baa5ad6eb2af8b1f284586d to your computer and use it in GitHub Desktop.
A custom property drawer for matrices
using System;
using UnityEditor;
using UnityEngine;
[CustomPropertyDrawer(typeof(Matrix4x4))]
public sealed class Matrix4x4Drawer : PropertyDrawer
{
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
return (EditorGUIUtility.singleLineHeight + 2) * 4 - 2;
}
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
float labelWidth = EditorGUIUtility.labelWidth;
float lineHeight = EditorGUIUtility.singleLineHeight;
float indent = EditorGUI.indentLevel * 14;
GUI.Label(new Rect(position.x + indent, position.y, labelWidth - indent, lineHeight), label);
float left = position.x + labelWidth;
float width = (position.width - labelWidth) / 4;
for (int y = 0; y < 4; y++)
{
for (int x = 0; x < 4; x++)
{
property.Next(true);
// The math here probably could be simplified. I wanted to make sure the gaps between the
// columns are exactly 2 pixels at all times. Because aesthetics.
float x0 = Mathf.Round(left + width * x) + 2;
float x1 = Mathf.Round(left + width * (x + 1));
var rect = new Rect(x0 - 15, position.y + y * (lineHeight + 2), x1 - x0 + 15, lineHeight);
// Avoid displaying useless values values like 6.123234e-17
float oldValue = (float)Math.Round(property.floatValue, 6);
float newValue = EditorGUI.FloatField(rect, oldValue);
if (newValue != oldValue)
property.floatValue = newValue;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment