Search code examples
c#unity-game-enginegame-development

How to change list name based on method parameter


So I have multiple lists and based on the input to method parameter I want to change which list we will be looking into.

public int GetGrowthTime(string crop) //get the growth time of matching crop from list
    {
        Debug.Log($"{crop}Data");  //wheatData
        Debug.Log("type of " + ($"{crop}Data".GetType()));  //System.String
        return ($"{crop}Data"[0]);     //119
    }

I have written the outputs on the right as comments, unfortunately I can't take {crop}Data out of "" and I don't know any other way to do this. The output of return should've been 60


Solution

  • This seems like a good opportunity to use a Dictionary, which is a generic collection of unique keys and associated values. In your specific case, you might have a Dictionary with a string key and a List<int> value:

    // The key will be the crop name, and the value is the list of growth times
    Dictionary<string, List<int>> cropGrowthTimes = new Dictionary<string, List<int>>();
    
    // At some point, you'll populate the Dictionary - maybe in your Start or Awake?
    // [...]
    
    public int GetGrowthTime(string crop)
    {
        // Now we can directly retrieve the list we want using the supplied crop
        return cropGrowthTimes[crop][0];
    }