Generate unique ID on object creation?

I would like to generate a unique GUID when an object is placed into the scene that never changes. This is for purposes of saving and reloading my game. I need to be able to associate each object with some kind of unique value and I would prefer a generic solution than to use the object name or its name+position.

I tried this C# editor script:

using UnityEditor;
using UnityEngine;

[CustomEditor( typeof( Guid ) )]

class GuidInspector : Editor
{
	public override void OnInspectorGUI()
	{
		Guid guid = (Guid)target;
		if ( guid.guid == System.Guid.Empty )
		{
			guid.guid = System.Guid.NewGuid();
			GUI.changed = true;
		}

		EditorGUILayout.SelectableLabel( guid.guid.ToString() );

		if ( GUI.changed )
		{
			EditorUtility.SetDirty( target );
		}
	}
}

And this is the GUID script that I would attach to my object prefabs:

using UnityEngine;

public class Guid : MonoBehaviour 
{
	[HideInInspector]
	public System.Guid guid;
}

It seems to work and the GUID persists through save and reload, but as soon as I launch the player, it generates a new GUID. I tried putting code into an OnEnable function and that didn’t work. I searched around for some kind of event that runs when an object is created in the editor and I can’t find anything. Is there a way to do this?

Just create a function in every object that gets called which assigns the GUID, and sets a variable to false, so the GUID persists… Or maybe I’m totally wrong…

MonoBehaviour has a unique id for every object built in :

http://docs.unity3d.com/Documentation/ScriptReference/Object.GetInstanceID.html?from=MonoBehaviour

I wish it was that easy, but GetInstanceID returns a different value every time you load the scene. I need something that is generated when the object is placed into the scene via the editor and never changes. That means the same value every time I load the scene, every time I run the game, quit, reload, reboot, whatever.

Right now the only thing I can think of to do is combine the object’s name, scene name, and XYZ position into a string. Which is fine as long as objects never move or share the same location with another object, but that is pretty limiting.

6 Likes

I made another editor script that generates GUIDs for every object in my scene. I just have to remember to run it any time I place new objects. Which is annoying, but at least I can make progress.

public class GenerateGuids : ScriptableWizard
{
	[MenuItem( "Custom/Generate Guids" )]
	static void Generate()
	{
		var objList = GameObject.FindObjectsOfType( typeof( GameObject ) );
		foreach ( var obj in objList )
		{
			Guid guidObj = ( (GameObject)obj ).GetComponent<Guid>();
			if ( guidObj != null )
			{
				if ( guidObj.guid == System.Guid.Empty )
				{
					guidObj.Generate();

					GUI.changed = true;
					EditorUtility.SetDirty( guidObj );
				}
			}
		}
	}
}

It sure would be nice if there were a way to get this to run automatically whenever I place a new object in the scene.

If you really want to blow some cycles while in the editor perhaps EditorApplication.hierarchyWindowChanged to regenerate your list quickly.

Why are you using GUI.changed? GUI.changed returns true if contents of the previous GUI element changed, and I’m quite sure your GUI.changed would return false every time as labels don’t change value (they’re not editable). Have you actually witnessed SetDirty being called (Log.Debug) Why not set the object dirty right after you create a new GUI?

Also, you should do the guid setting in OnEnable, not in OnInspectorGUI. It might happen that the OnInspectorGUI doesn’t get called (it’s not visible etc). And you should try NOT to have side-effects in your GUI rendering anyway.

using UnityEditor;
using UnityEngine;

[CustomEditor( typeof( Guid ) )]

class GuidInspector : Editor
{
	public void OnEnable()
	{
		Guid guid = (Guid)target;
		if ( guid.guid == System.Guid.Empty )
		{
			guid.guid = System.Guid.NewGuid();
			EditorUtility.SetDirty( target );
		}
	}

	public override void OnInspectorGUI()
	{
		Guid guid = (Guid)target;
		
		EditorGUILayout.SelectableLabel( guid.guid.ToString() );
	}
}

Also, are you sure that the System.Guid serializes properly? Have you actually managed to get the save/load thing to work?

1 Like

I set GUI.changed to true on line 14, then check for it on line 19 before setting the object dirty. If you don’t set GUI.changed to true when you change something, then you have to click off the object and click back to get its properties panel to update.

This code was a template from another inspector that I wrote that had several fields that could change. For this case, yes, I could have made it simpler. Also, I tried OnEnable at one point and it had the same issue so the problem didn’t appear to be with the inspector.

I figured that out eventually. :slight_smile: I had to change it to store the guid as a string to get it to save. Maybe that’s the problem. I never went back and retested my original inspector after changing the guid to a string so maybe that was it.

If you know of a way to get a real guid to serialize, please let me know! Is there a way to serialize a custom type?

Yeah it looks like the problem was me trying to serialize a System.Guid. It appears to be working now. I changed it to serialize the guid as a string and convert it back the first time someone accesses it. Thanks for your help. Here are the final scripts.

Guid.cs

using UnityEngine;

public class Guid : MonoBehaviour 
{
	[SerializeField]
	private string guidAsString;

	private System.Guid _guid;
	public System.Guid guid
	{
		get
		{
			if ( _guid == System.Guid.Empty
				 !System.String.IsNullOrEmpty( guidAsString ) )
			{
				_guid = new System.Guid( guidAsString );
			}
			return _guid;
		}
	}

	public void Generate()
	{
		_guid = System.Guid.NewGuid();
		guidAsString = guid.ToString();
	}
}

GuidInspector.cs

using UnityEditor;

[CustomEditor( typeof( Guid ) )]

class GuidInspector : Editor
{
	void OnEnable()
	{
		Guid guid = (Guid)target;

		if ( guid.guid == System.Guid.Empty )
		{
			guid.Generate();
			EditorUtility.SetDirty( target );
		}
	}

	public override void OnInspectorGUI()
	{
		Guid guid = (Guid)target;

		EditorGUILayout.SelectableLabel( guid.guid.ToString() );
	}
}
1 Like
string uniqueID(){
        DateTime epochStart = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
        int currentEpochTime = (int)(DateTime.UtcNow - epochStart).TotalSeconds;
        int z1 = UnityEngine.Random.Range (0, 1000000);
        int z2 = UnityEngine.Random.Range (0, 1000000);
        string uid = currentEpochTime + ":" + z1 + ":" + z2;
        return uid;
    }
1 Like

No need for any of that, use Guid.NewGuid().ToString()

2 Likes
  1. Just keep the GUID in a string form instead of coinverting is back and forth unless there’s a specific need for it. Strings in hash tables are fast.
  2. Test and generate GUID’s in the OnValidate event.
3 Likes

I actually wrote a library that handles this automatically. It even works with prefabs and the new prefab window.

https://github.com/ashblue/fluid-unique-id

@Ash-Blue Thank you. But it’s a bit difficult to install. I have got an error opening Unity Editor after edited the manifest. Could you help how to write the manifest correctly? Screesshot => Screenshot by Lightshot