How to dynamically construct a reference to a game object by name

Hi - I have game objects tagged MenuOption0, MenuOption1, MenuOption2, etc. I want to keep a currentIndex var, which gets incremented each time the user swipes on the controller. That swipe should increment the currentIndex var, and switch the reference to a new game object, whose text color will be changed.

In this approach the objects you call MenuOptionX would need a script attached to each, which is MenuItem in the above example. This script uses Awake (it's exactly like Start, but all Awakes are completed before the Starts are executed).

MenuItems thus register themselves with the supervisor during the Awake phase (which is before the Start phase).

I assume you want the list in order, so I've added an IComparer example to sort the menu items by name, which you could customize for any sorting order you'd prefer.

The supervisor's Start function, which should be called after all the menu items have registered, sorts the list by name. Take care of your naming convention as MenuOption1 and MenuOption10 would precede MenuOption2 when sorted this way. You may do better with MenuOption01, 02, 03....

In any event, you now have a List which you can address as an array using an index, where each entry is a MenuItem, such that

@mheavers Perhaps I'm not understanding the totality of what you're trying to accomplish but I feel like the best way you approach this, due to the similar nature of the objects you're referencing, is with a collection:

MenuOptions collection: Order the MenuOptions into a container (list, array, etc) on startup. Then whenever your input logic needs to use a new MenuOption, you can just use the reference from your master list. That should let you grab the reference you need by the index at runtime.

Alternatively: If searching by name is required, and you know the count of MenuOptions, you could similarly use a container and populate it at runtime with a loop. That would eliminate the need to frequently call GameObject.Find();