0 votes

I want to store a bunch of weak references to objects in a set-like datastructure. I am thinking of doing something like the following, where set is a dictionary:

set[obj.get_instance_id()] = weakref( obj )

I think this will work, but there isn't too much documentation of get_instance_id. It sounds straightforward, but I want to make sure there are no unspoken caveats. Will the above always result in only one weakref per object added to the list?

Also, I will be looping over the values more than looking them up. Would it be better to use an array, then?


asked Dec 30, 2019 in Engine by Aristonaut (30 points)

1 Answer

0 votes

Yup, your logic will work. The instance_id is unique for each object. It just gets incremented internally in the ObjectDB class - that's why there is no Object property for it.

I recommend just using the dictionary b/c it will give you some extra goodies that the array won't.

The Array will be faster, but not by much. I just ran a small test (3 times each) where I iterated an array/dict of 100 objects and the array did it in 175 usecs versus 195 usecs for the dictionary.

answered Dec 31, 2019 by 2D||!2D (379 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.