4

In Unity, it provides a function to get the instance of GameObject

GetInstanceID ()

While the instance id could differ GameObjects, but the function to get GameObject by instance id

InstanceIDToObject()

is only provided in EditorUtility, which can't use in release.

As far as I think, using HashTable maybe is a method to reach that, but is t here any other method to achieve that?

1
  • The only way that might be possible is through reflection but that's not worth it due to performance reasons. Stick to HashTable or Dictionary. Commented May 17, 2017 at 6:33

2 Answers 2

9

Solution can be found on Unity forums, I'll quote for convenience.

Not directly, but you can use the InstanceID to rename the object, and then do a GameObject.Find using the InstanceID to access the object that way.

gameObject.name = GetInstanceID().ToString();
var foo = 38375; // A made-up InstanceId...in actual code you'd get this from a real object...you can store the instance ids in an array or something
GameObject.Find(foo.ToString()).transform.position = whatever;

I've also had a hashtable and used the instance ids as keys for the hashtable in order to access each object. You can go through and assign objects an identifier yourself, but since every object has a unique InstanceID() anyway, might as well use it if the situation calls for it.

Source: https://forum.unity3d.com/threads/can-i-use-instanceid-to-access-an-object.12817/

Sign up to request clarification or add additional context in comments.

2 Comments

This should be accepted as answer. However, you should never have to Find an object, it a bad performance hit if you have too many of finds in your code. If you must, consider FindWithTag, it is faster, provided you don't put the same tag on too many objects. Generally, keep references of what you could have to find.
No it should not be accepted as the answer as it doesn't answer the question, it's a workaround that requires you to rename objects. A proper answer would not require that.
1
public static GameObject getObjectById(int id)
{
    Dictionary<int, GameObject> m_instanceMap = new Dictionary<int, GameObject>();
    //record instance map

    m_instanceMap.Clear();
    List<GameObject> gos = new List<GameObject>();
    foreach (GameObject go in Resources.FindObjectsOfTypeAll(typeof(GameObject)))
    {
        if (gos.Contains(go))
        {
            continue;
        }
        gos.Add(go);
        m_instanceMap[go.GetInstanceID()] = go;
    }

    if (m_instanceMap.ContainsKey(id))
    {
        return m_instanceMap[id];
    }
    else
    {
        return null;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.