wyy
wyy

Reputation: 545

Local gameobject variable doesn't work using switch method (Unity)

I know this is basic, but I couldn't find the answer. I have a function which should return game object of different types. I like using switch method to describe each type stuff. The error and line it occurs on is shown in the code below:

GameObject getElement(string type)
{
    GameObject newGO;

    switch(type)
    {
        case "A":
           newGO= functionWhichReturnsGameObjectWithTypeA();
           break;
        case "B":
           newGO= functionWhichReturnsGameObjectWithTypeB();
           break;
    }

    return newGO; // error: Use of unassigned local variable 'newGO'
}


GameObject myGO = getElement("A");

Upvotes: 3

Views: 338

Answers (2)

asaf92
asaf92

Reputation: 1855

You need to give newGO a value in every execution flow, so have a default case where you either throw an exception if the type argument should be either "A" or "B" and newGO should never null, or simply set it to null if possible.

This should work:

GameObject newGO;

switch(type)
{
    case "A":
       newGO= functionWhichReturnsGameObjectWithTypeA();
       break;
    case "B":
       newGO= functionWhichReturnsGameObjectWithTypeB();
       break;
    default:
       throw new ArgumentException("Unexpected argument");
}

or:

default:
   return null;

Upvotes: 3

wyy
wyy

Reputation: 545

Thanks to @Stefan comment, this did the trick:

GameObject newGO = null; 

Upvotes: 0

Related Questions