Accessing an array with a string

Hi. This is my firs post of the forum and my English is not perfect. So, if i do something wrong, sorry already now.

I have arrays in my project and i want to access one of them with a string. For example;

//I have this arrays.
public string[] ARGENTINAcities;
public string[] BRAZILcities;
public string[] PERUcities;
public string[] MEXICOcities;

//I have a Text.
public Text cityname;

public void countryclick()
    {
        //When i click the button, i get its name as a string with "countryname". 
        //Like this, i click the "ARGENTINA" button and "countryname" becomes "ARGENTINA".
        string countryname = EventSystem.current.currentSelectedGameObject.name;
        //arrayname is that what i want to use to access arrays. 
        //Like this, arrayname = ARGENTINAcities;
        arrayname = countryname + "cities";
        //And here, i want to use "arrayname" as an array name to access its elements. 
        //Like this, cityname.text = arrayname[2];
    }

I will be glad if you help me.

You would need to put each array into a Dictionary to find it.

public Dictionary<string,string[]> CityLists = new Dictionary<string,string[]>();

And then in Start():

CityLists["ARGENTINA"] = ARGENTINAcities;
CityLists["BRAZIL"] = BRAZILcities;

Then you can access them with:

string CityName = "ARGENTINA";

string[] CityList = CityLists[CityName];

I highly recommend you look into using JSON and loading that instead. That way if you add cities or countries, you do not need to recompile your program code.

Another way of organizing it is to place each array of city names into a ScriptableObject, which also gets you away from changing code every time you change data.

3 Likes

You could also use a switch statement.

public string[] GetCitiesArray(string countryName)
{
    string[] returnArray = null;

    switch(countryName)
    {
        case "ARGENTINA":
            returnArray = ARGENTINAcities;
            break;
        case "BRAZIL":
            returnArray = BRAZILcities;
            break;
        case "PERU":
            returnArray = PERUcities;
            break;
        case "MEXICO":
            returnArray = MEXICOcities;
            break;
        default:
            Debug.Log("Uhhh, ohhh, GetCitiesArray called with a bad countryName: " + countryName);
            break;
    }
    return returnArray;
}
2 Likes

Thank you so much Kurt. This is a very useful solution and I will learn JSON using. Thank you again.

1 Like

Thanks for your time and answer me Joe. I will keep switch/case statement in my mind and i will try to use it often. Thank you again.

2 Likes