4

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.

Blue
  • 820
  • 4
  • 17
N8W1nD
  • 53
  • 6
  • 2
    The open is opened, but don't you have any controller or bootstrap on the scene that you can setup, and this controller can store the reference of the object that you need to call? – Lotan Apr 04 '23 at 17:17

2 Answers2

2

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.

DylanT 25
  • 233
  • 1
  • 7
  • Thank you for your answer! I ended up adding a monobehaviour to an object already tagged for test purposes, that stores test-relevant references as variables (not as lists, as I wanted to access them by name). I first wanted to store them in a dictionary but this is not serializable (without additional packages) :D But I will create a singleton, as I dont need to access anything via tags then. – N8W1nD Aug 09 '23 at 14:35
  • Really not an expert, but what @N8W1nD did is what I would consider best practice: create a scene fixture with the instantiated GameObjects in it and have a singleton to store the test-relevant references. – David Cian Aug 22 '23 at 11:38
0

You can set unique IDs to game objects and then you can get all game objects with that script (or relevant component) on it and find which is needed by checking their IDs.

If you give information about what the scenario about maybe people can help you better.

msaiduraz
  • 151
  • 5
  • 1
    Can you elaborate on the implementation of this method? Because the above ways mentioned by OP are the preferred ones, and anything other than that is just an unnecessary hassle. – Geeky Quentin Apr 04 '23 at 15:02