Adding Components by their string parameters

I currently created this function to add Components to a gameObject and set some parameters of those.

Sadly i had to create multiple switches, because i do not know how to parse a string into a component correctly.

foreach (KeyValuePair<string, Dictionary<string, float>> effect in dic)
{
    switch (effect.Key)
    {
        case "AudioLowPassFilter":
            go.AddComponent<AudioLowPassFilter>();

            foreach(KeyValuePair<string,float> param in effect.Value)
            {
                switch (param.Key)
                {
                    case "cutoffFrequency":
                        go.GetComponent<AudioLowPassFilter>().cutoffFrequency = param.Value;
                        break;
                    default:
                        break;
                }
            }
            break;
        case "AudioEchoFilter":
            go.AddComponent<AudioEchoFilter>();
            foreach (KeyValuePair<string, float> param in effect.Value)
            {
                switch (param.Key)
                {
                    case "delay":
                        go.GetComponent<AudioEchoFilter>().delay = param.Value;
                        break;
                    case "decayRatio":
                        go.GetComponent<AudioEchoFilter>().decayRatio = param.Value;
                        break;
                    default:
                        break;
                }
            }
            break;
        default:
            break;
    }
}

I am sure there must be a better solution. Any help would be appreciated.

Where are you getting this Dictionary dic from? Why not use a more structured piece of data like a class or struct with actual fields? That would be simpler than string comparisons.

1 Like

i know. i will implement a new data structure as soon as i get it to work. That’s why i am asking.

I need a better way to add Unity Components by their string names or implement components directly into the data structure. Dont know if this is possibly to be honest.

Couldn’t you use Type objects?

var componentType = typeof(AudioLowPassFilter);

myGameObject.AddComponent(componentType);