greyBow
greyBow

Reputation: 1348

Return a GameObject from a switch statement

What is the correct way to return a GameObject from a switch statement? When I try to return avatar I get the error 'use of unassigned local variable 'avatar''. I'm a little mixed up on how to get the return to work with a switch statement. Thanks for the help!

private GameObject GetAnimalAvatar(string animal)
{
    GameObject avatar;

    switch (animal)
    {
        case "bear":
            avatar = ForestGameManager.fgm.bearAvatar;
            break;

        case "boar":
            avatar = ForestGameManager.fgm.boarAvatar;
            break;

        case "doe":
            avatar = ForestGameManager.fgm.doeAvatar;
            break;

        default:
            break;
    }

    return avatar;
}

Upvotes: 0

Views: 1028

Answers (1)

Programmer
Programmer

Reputation: 125315

The avatar variable will not be initialized if none of case conditions is met since it's just declared as GameObject avatar; leading to that error.

You have two options:

1.Initialize or set the avatar variable to null in the default check. This means that if none of the cases condition is met, the default one will execute and your case will be set to null.

switch (animal)
{
    case "bear":
        avatar = ForestGameManager.fgm.bearAvatar;
        break;

    case "boar":
        avatar = ForestGameManager.fgm.boarAvatar;
        break;

    case "doe":
        avatar = ForestGameManager.fgm.doeAvatar;
        break;

    default:
        //INITIALIZED TO NULL
        avatar = null;
        break;
}

2.Set it to null where it is declared:

Change

GameObject avatar;

to

GameObject avatar = null;

Upvotes: 6

Related Questions