HoyHym Ho
HoyHym Ho

Reputation: 79

for-loop calling strings to turn into booleans

This is prob a really dumb question but I'm stuck on this one...

So I have a bunch of booleans called monster1, monster2, ...

And I want to use a for-loop to toggle the respective booleans for the col.name s . The col.name returns monster1, monster2, ... and I don't know how to turn those strings into booleans

private void OnTriggerExit2D(Collider2D col)
{
    for (var i = 0; i < 9; i++)
    {
        if (col.name == "monster" + i)
        {
            "monster" + i = false;
        }
    }
}

Upvotes: 2

Views: 40

Answers (2)

sɐunıɔןɐqɐp
sɐunıɔןɐqɐp

Reputation: 3512

In case you need to refer to the monster by its ID, a simple Dictionary is recommended.

Also, remember that dictionaries may have worse performance than arrays. Unless you are dealing with >10.000 monsters, this should not be an issue.

Dictionary<string, bool> Monsters = new Dictionary<string, bool>();

private void OnTriggerExit2D(Collider2D col)
{
    for (var i = 0; i < 9; i++)
    {
        string monsterID = "monster" + i;
        Monsters[monsterID] = col.name != monsterID;
    }
}

Then you may later use it like this:

if(Monsters["monster3"])
    // Do something...

Upvotes: 1

Mureinik
Mureinik

Reputation: 311393

Why not use an array of booleans?

private void OnTriggerExit2D(Collider2D col)
{
    for (var i = 0; i < 9; i++)
    {
        if (col.name == "monster" + i)
        {
            monster[i] = false;
        }
    }
}

Upvotes: 6

Related Questions