@mheavers
It’s the etc. that makes the setup such an unattractive proposition. When there’s 8, or 20 or more, it gets ugly.
I assume a supervisory script owns the code you posted. I’ll call it a class MenuSupervisor. Something like:
public class MenuItem : MonoBehaviour
{
void Awake() { MenuSupervisor.RegisterMenuItem( this ); }
}
public class MenuComp : IComparer< MenuItem >
{
public int Compare( MenuItem a, MenuItem b )
{
return System.String.Compare( a.gameObject.name, a.gameObject.name );
}
}
public class MenuSupervisor : MonoBehaviour
{
private static List< MenuItem > menuEntries;
public static void RegisterMenuItem( MenuItem m )
{
menuEntries.Add( m );
}
void Start()
{
menuEntries.Sort( new MenuComp() );
}
}
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
List[ x ].gameObject.GetComponent<TextMeshProUGUI>().color = colorWhite
Would work for any x. Well, any x that’s within List.
Of course, the MenuItem could use Start to cache the TextMeshProUGUI if you like.