- Home /
Using Debug.Log to output the memory address of a GameObject
I would like to get the variable address of the gameobject using Debug.Log rather than just the name of the GameObject. Bonus points for output being in hex.
Thanks for your time.
jrhowa
Answer by Bunny83 · Aug 24, 2016 at 10:27 AM
Managed references don't directly relates to memory addresses. Where the objects actually are in memory could even change if the GC decides to. So the memory location doesn't have to be constant during the lifetime of an object. Only pinned objects will stay at the same address, however having a lot pinned object can have a bad impact on the GC as it can't optimies the memory if objects are locked in place.
Dealing with actual pointers and memory addresses requires you to use unsafe code.
Like tanoshimi said: Why do you need this? You might want to use "GetHashCode()" instead which returns an int value for that specific object. Of course Hash values don't have to be unique. All objects derived from UnityEngine.Object also have an instance ID (GetInstanceID()).
If you really want to read the memory location, see this SO post.
To display a 32bit integer value as hex string, just use val.ToString("X8")
. Of course 64 bit values would need 16 digits.
ps: You also should differenciate between an object address and a variable address. A GameObject reference variable has itself a location in memory regardless what that reference references. But before we go more in detail you should tell use what's the point of that.
@Bunny83 To setup more info on what I was trying to do is. Let's say I Instantiate 10 objects from the same prefab, I want to in some way find what object I'm looking at. You ended up telling me what I needed even tho the way I asked it was a bit off the mark. In other systems, I would do this by looking at the pointer to memory.
In short, GetInstanceID was the thing I was looking for. Just ended up going the long way around to find it.
Thanks.
Actually Debug.Log has a two parameter version which allows you to pass any object derived from UnityEngine.Object along. This will be highlighted when you click on the log in the console if the object is a scene object or an asset.
Furthermore any public variable (which shows up in the inspector) to other objects can be clicked on and the referenced object is highlighted