Skip to content

Instantly share code, notes, and snippets.

@luke161
Created October 13, 2017 09:34
Show Gist options
  • Save luke161/96fdf54cc3022607fc8f724f920fd352 to your computer and use it in GitHub Desktop.
Save luke161/96fdf54cc3022607fc8f724f920fd352 to your computer and use it in GitHub Desktop.
Unity Editor extension to generate unique identifiers for strings. Shows a 'Generate' button next to a string input field in the inspector, for any string property where a [UID] attribute is assigned. For example: [UID] public string id;
using UnityEngine;
// Example usage:
// [UID] public string id;
public class UIDAttribute : PropertyAttribute
{
}
using UnityEngine;
using UnityEditor;
using System;
[CustomPropertyDrawer(typeof(UIDAttribute))]
public class UIDAttributeDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
//UIDAttribute range = attribute as UIDAttribute;
if (property.propertyType == SerializedPropertyType.String) {
Rect idRect = new Rect (position.x, position.y, position.width-70, EditorGUIUtility.singleLineHeight);
Rect buttonRect = new Rect (position.x+(position.width-70), position.y, 70, EditorGUIUtility.singleLineHeight);
EditorGUI.PropertyField (idRect, property);
if (GUI.Button (buttonRect, "Generate")) {
property.stringValue = Generate(false,true,true);
}
} else
EditorGUI.LabelField(position, label.text, "Use UID with string values");
}
private string Generate(bool getSecondsNotTicks, bool getMillisecondsNotTicks, bool getHexValue)
{
string id = string.Empty;
DateTime historicalDate = new DateTime(1970, 1, 1, 0, 0, 0);
if (getSecondsNotTicks || getMillisecondsNotTicks)
{
TimeSpan spanTillNow = DateTime.UtcNow.Subtract(historicalDate);
if (getSecondsNotTicks)
id = String.Format("{0:0}", spanTillNow.TotalSeconds);
else
id = String.Format("{0:0}", spanTillNow.TotalMilliseconds);
}
else
{
long ticksTillNow = DateTime.UtcNow.Ticks - historicalDate.Ticks;
id = ticksTillNow.ToString();
}
if (getHexValue)
id = long.Parse(id).ToString("X");
return id;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment