Uniquely identify objects ?

Hi, I’d like to identify objects or components in a unique way, but it seems that GetHashCode() or GetInstanceId() are different each time I build my projet. I know I could setup the name to identify uniquely my objects, but this may lead to other issues. Is there any other easy solution apart from creating custom code ?

Well there are two ways of looking at this:

  • Ensure that the name of an object is unique
  • Create and store a unique identifier for the object

You can create a unique Id using something like this:

   public string Id = Guid.NewGuid().ToString();

GetHashCode() changes as your properties and fields change (probably, depends on the implementation). GetInstanceId() is doing something with the memory address the object is currently at. There is some script here that will make objects have unique names.

You can store index ID using PlayerPrefs. Effectively, Unity ID are different each time.

using UnityEditor;
using UnityEngine;

public class UniqueID{

	public int ID;

	static string key = "UniqueID";

	public UniqueID(){


			this.ID = PlayerPrefs.GetInt(key);


		this.ID = 0;



[CustomPropertyDrawer (typeof (UniqueID))]
public class UniqueIDDrawer : PropertyDrawer {

	public override void OnGUI (Rect position, SerializedProperty property, GUIContent label) {

		EditorGUI.BeginProperty (position, label, property);
		position = EditorGUI.PrefixLabel (position, GUIUtility.GetControlID (FocusType.Passive), label);
		int indent = EditorGUI.indentLevel;
		EditorGUI.indentLevel = 0;
		string value = property.FindPropertyRelative ("ID").intValue.ToString();
		Rect IDRect = new Rect (position.x, position.y, 25f + value.Length * 6f, position.height+2f);
		EditorGUI.indentLevel = indent;
		EditorGUI.EndProperty ();



How to use:

using UnityEngine;
using System.Collections;

public class script : MonoBehaviour {

	public UniqueID ID;


IMPORTANT: If you copy/paste GameObject or component, remember “Reset” the component to create unique ID.