Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the reference to a GameObject in a Unit Test in Unity from an opened scene?

I know of several methods, but they all have drawbacks I would like to avoid:

  1. The obvious way would be to use GameObject.Find(), but this breaks, as soon as the object gets renamed (and is very costly). Thus I would like to avoid using it.
  2. FindObjectOfType() will not guarantee, that the correct object is found (there are several objects with the relevant component).
  3. The last alternative I know of, is using GameObject.FindWithTag(), for which I would need to introduce a tag to the object, while tags are not used in other parts of the project, thus I would break existing conventions.

Is there another solution/best practice for this problem you know of?

I tried researching other ways, but did not find a completely suitable approach, as described above.

like image 991
N8W1nD Avatar asked Sep 16 '25 21:09

N8W1nD


1 Answers

If the objects are already in the scene when the game starts, just use a List<>, and populate it manually in the editor. Then you can run through the list to find the correct object.

If the objects are generated during gameplay, then you can assign them to a List<> when they are created.

To access the list from any place, make it's script an instance (Singleton Class), and you can simply reference the instance from anywhere.

Check out the code in the answer given here for how to properly implement a Singleton Class.

like image 170
DylanT 25 Avatar answered Sep 19 '25 15:09

DylanT 25