i have a String with the VALUE "abc" and want to set a bool with the NAME "abc" to true based on the string value

Hey guys!

I wont paste in my code cause its in to many different classes so i will try to simplify my problem and give an example like this:

So i have a Class “Enemy”
This class has a string type.
From this i have made a few Enemys like “Wizard : Enemy” with type “wizard”, “Goblin : Enemy” with type “goblin”, “Random Dude : Enemy” with type “random dude” and many more.
Each of those can exist only once and will not spawn again from my random enemy spawner until this one copy exists.
The Spawner has some booleans wizard, goblin, randomDude and many more.
The spawner spawns the object from a list of Enemys. This one changes every time.

So now i need a function to take the type and the equivalant bool and to check if it already is spawned.

I tried to do this with a Reflection but i have heard that reflections are slow so i am looking for a better solution.

Here is the Method that i wanted to use to “convert” the string name into a bool. I dont really want a Switch cause there will be many enemys.

    public bool isSingleCopySpawned(string type)
    {
        string typeActive = type + "Active";
        print(typeActive);
        bool boolActive = (bool)this.GetType().GetField(typeActive).GetValue(this);
        print(boolActive);
        return boolActive;
    }

Hi! You should use a Dictionary (aka Map) Look here
Your dictionary will be of type <String, bool>. You can use the methods Add(String key, bool value), and ContainsKey(String key)

Im not sure a dictionary is a good solution but I am also not sure what the problem is.


You have a spawner and it spawns objects from a list of enemies, the spawned enemy changes every time.


So why not just create the enemies once and just recycle the instances using object pooling? That way there will only ever be as many as you have ever created. You wont hit any garbage collection performance spikes in deallocating them All you need to do is pick a random enemy from the pool and put it into the game when you want.


If you do that and access them by using a string then I guess you could put them in a dictionary but it wouldnt be a string bool dict it would probably be better as a string GameObject one.

i.e.

Dictionary<string, GameObject> Enemies = new Dictionary<string, GameObject>
{
    { "Wizard", Wizard },
    ...
}