Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 421
deadmarston Avatar asked Nov 07 '25 23:11

deadmarston


1 Answers

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/

like image 102
Bazgrim Avatar answered Nov 12 '25 16:11

Bazgrim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!