Last Updated: November 19, 2020
·
7.641K
· ultrakorne

Generate a unique id in Unity using a property drawer

The goal
In a scriptable object or prefab sometimes you need a unique id to identify the asset, would be nice to just mark a string with an attribute

[UniqueIdentifier]
public string uniqueId;

and in the inspector get a read only label displaying a unique id for that asset, assigned to your ivar and ready to use at runtime.

Picture

How to:

First you need to define the attribute, in this case we just need a type, so define somewhere:

public class UniqueIdentifierAttribute : PropertyAttribute { }

Then write a custom property drawer. as it is an editor script, the next file need to be placed in the Editor dir in unity.

using UnityEditor;
using UnityEngine;

[CustomPropertyDrawer (typeof(UniqueIdentifierAttribute))]
public class UniqueIdentifierDrawer : PropertyDrawer
{
    public override void OnGUI (Rect position, SerializedProperty prop, GUIContent label)
    {
    string assetPath = AssetDatabase.GetAssetPath (prop.serializedObject.targetObject.GetInstanceID ());
    string uniqueId = AssetDatabase.AssetPathToGUID (assetPath);    

    prop.stringValue = uniqueId;

    Rect textFieldPosition = position;
    textFieldPosition.height = 16;
    DrawLabelField (textFieldPosition, prop, label);
}

void DrawLabelField (Rect position, SerializedProperty prop, GUIContent label)
{
    EditorGUI.LabelField (position, label, new GUIContent (prop.stringValue));
} 
}

Related protips:

Improved PlayerPrefs for Unity

2 Responses
Add your response

Sadly it isn't generating a unique ID with Unity 4.5 for me. Let me know at @ashbluewd on Twitter if you know of a fix.

over 1 year ago ·

This should work if the property drawer is applied to a scriptable object, or a prefab not in the scene (Instantiate it at runtime will retain the id set)

over 1 year ago ·