我知道这是基本的,但我找不到答案。我有一个函数应该返回不同类型的游戏对象。我喜欢使用 switch 方法来描述每种类型的东西。错误和它发生的行显示在下面的代码中:
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");
最佳答案
你需要在每个执行流程中给 newGO
一个值,所以有一个默认情况,如果 type
参数应该是 你要么抛出异常“A”
或 “B”
和 newGO
永远不应为 null,或者尽可能将其设置为 null。
这应该有效:
GameObject newGO;
switch(type)
{
case "A":
newGO= functionWhichReturnsGameObjectWithTypeA();
break;
case "B":
newGO= functionWhichReturnsGameObjectWithTypeB();
break;
default:
throw new ArgumentException("Unexpected argument");
}
或:
default:
return null;
关于c# - 本地游戏对象变量不能使用 switch 方法 (Unity),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58518461/