Skip to content

Instantly share code, notes, and snippets.

@DmitriyYukhanov
Created March 21, 2017 11:18
Show Gist options
  • Save DmitriyYukhanov/5d93a0a204c32db1dd45d7a86e1df87e to your computer and use it in GitHub Desktop.
Save DmitriyYukhanov/5d93a0a204c32db1dd45d7a86e1df87e to your computer and use it in GitHub Desktop.
Updated code to get a Unity object id.
#define UNITY_5_PLUS
#if UNITY_4_5 || UNITY_4_6 || UNITY_4_7 || UNITY_4_8 || UNITY_4_9
#undef UNITY_5_PLUS
#endif
using UnityEngine;
using System.Reflection;
using UnityEditor;
namespace CodeStage.Maintainer.Tools
{
public class ObjectTools
{
private static PropertyInfo cachedInspectorModeInfo;
internal static long GetLocalIdentifierInFileForObject(Object unityObject)
{
long id = -1;
if (unityObject == null) return id;
if (cachedInspectorModeInfo == null)
{
cachedInspectorModeInfo = typeof(SerializedObject).GetProperty("inspectorMode", BindingFlags.NonPublic | BindingFlags.Instance);
}
SerializedObject serializedObject = new SerializedObject(unityObject);
cachedInspectorModeInfo.SetValue(serializedObject, InspectorMode.Debug, null);
SerializedProperty serializedProperty = serializedObject.FindProperty("m_LocalIdentfierInFile");
#if UNITY_5_PLUS
id = serializedProperty.longValue;
#else
id = serializedProperty.intValue;
#endif
if (id <= 0)
{
PrefabType prefabType = PrefabUtility.GetPrefabType(unityObject);
if (prefabType != PrefabType.None)
{
id = GetLocalIdentifierInFileForObject(PrefabUtility.GetPrefabParent(unityObject));
}
else
{
// this will work for the new objects in scene which weren't saved yet
id = unityObject.GetInstanceID();
}
}
if (id <= 0)
{
GameObject go = unityObject as GameObject;
if (go != null)
{
id = go.transform.GetSiblingIndex();
}
}
return id;
}
}
}
@DmitriyYukhanov
Copy link
Author

DmitriyYukhanov commented Jul 19, 2019

Also please note, there is a more elegant way for 2018.2 or newer:

public static long GetAssetLocalIdentifierInFile(Object unityObject)
{
	string guid;
	long id;

	if (!AssetDatabase.TryGetGUIDAndLocalFileIdentifier(unityObject, out guid, out id))
	{
		return -1;
	}

	return id;
}

@RiskyWilhelm
Copy link

RiskyWilhelm commented Sep 2, 2024

there is a more elegant way

You are wrong. This wont work for Components that is inside the scene. For that reason, they created some kind of ID Obtainer named "GlobalObjectId". It works if you want to get the ID and GUID. But still, if you want to check if it is an instantiation or persistent, when you check a new instantiation via GlobalObjectID, hilarously it creates a new whole localID and assigns the GUID. So currently, they just blocked all of the ways to check whether it is instantiated or not. From the first stage, they should have been added that into their UnityEngine.Object hence it is not System.Object .D

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment