Call different function based on a boolean

I have a boolean in my function that decide what function to call. Both of the function that are beying called giving back an Array.

Now in my eyes Hex[] areaHexes does exists but the compiler does not compile because it thinks its not set ( does not exists ).

How do I call one of both function properly based on what value bool semiRandom has?

void ElevateArea(int q, int r, int range, bool semiRandom = false, float centerHeight = 1f)
{
    Hex centerHex = GetHexAt(q, r);

    if (semiRandom) 
    { 
        Hex[] areaHexes = GetSemiRandomHexesWithinRangeOf(centerHex, range);
    } 
    else
    {
        Hex[] areaHexes = GetHexesWithinRangeOf(centerHex, range);
    }

    foreach (Hex h in areaHexes)
    {
        //if (h.Elevation < 0)
            // h.Elevation =  0;

        h.Elevation += 0.5f * Mathf.Lerp(1f, 0.25f, Hex.Distance(centerHex, h ) / range);
    }
}
Jon Skeet
people
quotationmark

The reason it's not working is that you are currently declaring two local variables called areaHexes, each of which has a scope which is just the block they're declared in - so neither of them is in scope when you try to use them.

Brandon's answer (declaring the variable outside the if statement and then assigning to it from different places) will work fine - areaHexes is now in scope when you use it later. However, you can do it more simply with a conditional ?: operator:

Hex[] areaHexes = semiRandom
    ? GetSemiRandomHexesWithinRangeOf(centerHex, range)
    : GetHexesWithinRangeOf(centerHex, range);

people

See more on this question at Stackoverflow