Skip to content

Instantly share code, notes, and snippets.

@leventeren
Created August 23, 2023 15:00
Show Gist options
  • Save leventeren/b16f221eed31343f423c12ee6ecc2cee to your computer and use it in GitHub Desktop.
Save leventeren/b16f221eed31343f423c12ee6ecc2cee to your computer and use it in GitHub Desktop.

Add this script to a GameObject to give it a unique alphanumeric identifier.

Auto-generates an ID when the script is added to a GameObject Only one script per GameObject, meaning each GameObject gets only ONE unique ID Uses system GUID generation Unique ID can only be accessed, it cannot be overwritten by other scripts Custom Editor to show the ID in the inspector, and a button to reset it if needed Keeps the same ID throughout play-mode and in builds

// ------------------------------------------- //
// Author : William Whitehouse / WSWhitehouse //
// GitHub : github.com/WSWhitehouse //
// Created : 09/02/2020 //
// Edited : 10/02/2020 //
// ------------------------------------------- //
using UnityEngine;
namespace WSWhitehouse.UniqueID
{
[DisallowMultipleComponent]
public class UniqueID : MonoBehaviour
{
private void Awake()
{
if (string.IsNullOrEmpty(id))
{
Debug.LogError(gameObject.name + " :: Unique ID is Null or Empty");
}
}
[SerializeField] private string id;
public string ID => id;
}
}
// ------------------------------------------- //
// Author : William Whitehouse / WSWhitehouse //
// GitHub : github.com/WSWhitehouse //
// Created : 09/02/2020 //
// Edited : 10/02/2020 //
// ------------------------------------------- //
using System;
using UnityEditor;
using UnityEngine;
namespace WSWhitehouse.UniqueID.Editor
{
[CustomEditor(typeof(UniqueID))]
public class UniqueIDEditor : UnityEditor.Editor
{
private UniqueID _uniqueID;
private SerializedProperty _id;
public override void OnInspectorGUI()
{
_uniqueID = (UniqueID) target;
_id = serializedObject.FindProperty("id");
if (string.IsNullOrEmpty(_id.stringValue))
{
ResetUniqueID();
}
EditorGUILayout.BeginHorizontal(GUI.skin.box);
EditorGUILayout.LabelField(new GUIContent("Unique ID"), EditorStyles.boldLabel);
EditorGUILayout.LabelField(new GUIContent(_uniqueID.ID));
EditorGUILayout.EndHorizontal();
if (GUILayout.Button(new GUIContent("Reset ID")) && EditorUtility.DisplayDialog("Reset ID",
"Are you sure you want to reset the ID? You cannot change it back!", "Reset ID", "Cancel"))
{
ResetUniqueID();
}
}
private void ResetUniqueID()
{
Debug.Log(_uniqueID.gameObject.name + " :: RESETTING UNIQUE ID");
_id.stringValue = Guid.NewGuid().ToString();
EditorUtility.SetDirty(_uniqueID.gameObject);
serializedObject.ApplyModifiedProperties();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment