deadmarston
deadmarston

Reputation: 99

how to access GameObject by instance id in Unity

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?

Upvotes: 4

Views: 27650

Answers (2)

Taivas Gogoljuk
Taivas Gogoljuk

Reputation: 79

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;
    }
}

Upvotes: 1

Bazgrim
Bazgrim

Reputation: 189

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/

Upvotes: 9

Related Questions