Skip to content

Instantly share code, notes, and snippets.

@giacomelli
Last active April 16, 2024 12:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save giacomelli/bb3b4bf52e560c3d673cd3d50f563cfb to your computer and use it in GitHub Desktop.
Save giacomelli/bb3b4bf52e560c3d673cd3d50f563cfb to your computer and use it in GitHub Desktop.
using UnityEngine;
using System;
namespace Giacomelli.Framework
{
/// <summary>
/// TimeSpan Box Attribute - http://diegogiacomelli.com.br/unitytips-timespan-box-drawer
/// </summary>
[AttributeUsage(AttributeTargets.Field)]
public class TimeSpanBoxAttribute : PropertyAttribute
{
public TimeSpanBoxAttribute(string format)
{
Format = format;
}
public string Format { get; }
}
}
using UnityEngine;
using UnityEditor;
using System;
namespace Giacomelli.Framework
{
/// <summary>
/// TimeSpan Box Drawer - http://diegogiacomelli.com.br/unitytips-timespan-box-drawer
/// </summary>
[CustomPropertyDrawer(typeof(TimeSpanBoxAttribute))]
public class TimeSpanBoxDrawer : PropertyDrawer
{
const float XPadding = 30f;
const float YPadding = 5f;
const float Height = 20f;
public override void OnGUI(Rect position,
SerializedProperty property,
GUIContent label)
{
var attr = attribute as TimeSpanBoxAttribute;
var value = TimeSpan.FromSeconds(property.floatValue);
var text = FormatText(attr.Format, value);
EditorGUI.PropertyField(position, property, label, true);
position = new Rect(
XPadding,
position.y + EditorGUI.GetPropertyHeight(property, label, true) + YPadding,
position.width - XPadding,
Height);
EditorGUI.HelpBox(position, text, MessageType.None);
}
private string FormatText(string format, TimeSpan value)
{
format = format
.Replace(":", @"\:")
.Replace(".", @"\")
.Replace(@"0\:", "0:");
return string.Format(format, value);
}
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
return EditorGUI.GetPropertyHeight(property, label, true) + Height;
}
}
}
using Giacomelli.Framework;
using UnityEngine;
public class TimeSpanBoxDrawerUsage : MonoBehaviour
{
[TimeSpanBox("{0:mm} minutes and {0:ss} seconds")]
public float TimeInSeconds;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment