简体   繁体   中英

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;
}

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM