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

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.

This is what I'm trying as a test:

GameObject testText = GameObject.Find("MenuOption" + 4);
TextMeshProUGUI thisTextMesh = testText.GetComponent<TextMeshProUGUI>();
thisTextMesh.color = colorWhite;


How do I dynamically construct a reference to MenuOption1,2,3,4,etc? Or is there a better way to handle this without writing a big long conditional?

• GameObject.Find is pretty well not recommended in Unity unless you're really desperate Try tagging them, and use GameObject.FindWithTag. docs.unity3d.com/ScriptReference/GameObject.FindWithTag.html – Almo Jul 14 '18 at 1:16
• Would it be an option to simply store references to the gameObjects in an array or list? Then you can just increment your index into the collection, no searching involved at all. With a little more info about how these menu options are created/provided, we can demonstrate how to set up such a structure. – DMGregory Jul 14 '18 at 1:53

Maybe I'm misunderstanding you but if you have a GameObject and Color for each menu option, I would make a custom class to hold the data and then make an array of that class.

For example

using UnityEngine;

[System.Serializable]
{
public Color optionColor;
public GameObject optionPrefab;
}


then you can put it into an array, which you can do in the inspector or via code.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Switcher : MonoBehaviour
{
private int optionIndex = 0;

// Update is called once per frame
void Update ()
{
//
if (Input.GetKeyDown(KeyCode.A))
{
optionIndex += -1;
}

if (Input.GetKeyDown(KeyCode.D))
{
optionIndex += 1;
}

Debug.Log(options[optionIndex].optionColor);
Debug.Log(options[optionIndex].optionPrefab);
}
}


Make sure you keep the index between 0 and however many options you have, otherwise you will get "Argument is out of range." errors.

• Thanks! That was enough info for me to get it to work. Also, for anyone else who comes across this - the VRInput class automatically assigns keys A and D to the Swipe Left and Swipe Right actions, so don't add them in your code if you are already handling, for example, an increase or decrease in Option Index with a Swipe Left or Right listener. – mheavers Jul 16 '18 at 18:09