Skip to content

Instantly share code, notes, and snippets.

@bzgeb
Last active March 16, 2021 09:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bzgeb/8c389cfd8c59be262cc7071d25990ffe to your computer and use it in GitHub Desktop.
Save bzgeb/8c389cfd8c59be262cc7071d25990ffe to your computer and use it in GitHub Desktop.
Uuids for Unity GameObjects
How I added UUIDs to Unity Game Objects
using UnityEngine;
public class ExampleGameObject : MonoBehaviour
{
public Uuid m_Uuid;
/*
// Then the rest of your code goes here
*/
}
//NOTE: Don't forget to generate a new UUID when you instantiate an object!
[System.Serializable]
public class Uuid
{
public string uuid;
public static Uuid Generate()
{
Uuid newUuid = new Uuid {uuid = System.Guid.NewGuid().ToString()};
return newUuid;
}
}
//NOTE: This file goes in an Editor Folder!
using System;
using UnityEditor;
using UnityEngine;
[CustomPropertyDrawer(typeof(Uuid))]
public class UuidDrawer : PropertyDrawer
{
public override void OnGUI(Rect a_Position, SerializedProperty a_Property, GUIContent a_Label)
{
EditorGUI.BeginProperty(a_Position, a_Label, a_Property);
a_Position = EditorGUI.PrefixLabel(a_Position, GUIUtility.GetControlID(FocusType.Passive), a_Label);
int indent = EditorGUI.indentLevel;
EditorGUI.indentLevel = 0;
const int uuidButtonWidth = 80;
Rect uuidRect = new Rect(a_Position.x, a_Position.y, a_Position.width - uuidButtonWidth, a_Position.height);
Rect newUuidButtonRect =
new Rect(a_Position.x + uuidRect.width, a_Position.y, uuidButtonWidth, a_Position.height);
SerializedProperty uuidProperty = a_Property.FindPropertyRelative("uuid");
EditorGUI.SelectableLabel(uuidRect, uuidProperty.stringValue);
if (GUI.Button(newUuidButtonRect, "New Uuid"))
{
if (EditorUtility.DisplayDialog("Generate new UUID?",
"Generating a new UUID will break any data using the current uuid", "Yes", "Cancel"))
{
uuidProperty.stringValue = Guid.NewGuid().ToString();
}
}
EditorGUI.indentLevel = indent;
EditorGUI.EndProperty();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment