Created
March 21, 2017 11:18
-
-
Save DmitriyYukhanov/5d93a0a204c32db1dd45d7a86e1df87e to your computer and use it in GitHub Desktop.
Updated code to get a Unity object id.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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