Reputation: 545
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
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
Reputation: 545
Thanks to @Stefan comment, this did the trick:
GameObject newGO = null;
Upvotes: 0