我将我的Unity3D游戏从JS到C#,我也面临着一些问题,此功能:Unity3D C# - 范围的变量
void ReorientationNaming(GameObject g)
{
///find the cube and its bounds
GameObject tobename = g;
Bounds cubebound = tobename.renderer.bounds;
string namex;
string namey;
string namez;
GameObject[] allAxisList = GameObject.FindGameObjectsWithTag("AxisPlain");
foreach(GameObject allAxis in allAxisList)
{
Bounds axisbound = allAxis.renderer.bounds;
if (cubebound.Intersects(axisbound))
{
if (allAxis.name.Contains("x"))
{
namex = allAxis.name;
namex = namex.Substring(1,1);
//print("namex" + namex);
}
if (allAxis.name.Contains("y"))
{
namey = allAxis.name;
namey = namey.Substring(1,1);
}
if (allAxis.name.Contains("z"))
{
namez = allAxis.name;
namez = namez.Substring(1,1);
}
}
tobename.name = namex+namey+namez;//<-- this line is the problem!
}
}
最后一行给我的错误:
Assets/Cumetry/MainGameLogic.cs(136,41): error CS0165: Use of unassigned local variable `namex'
Assets/Cumetry/MainGameLogic.cs(136,41): error CS0165: Use of unassigned local variable `namey'
Assets/Cumetry/MainGameLogic.cs(136,41): error CS0165: Use of unassigned local variable `namez'
我相信是我声明字符串的方式。任何想法如何解决这个问题?
发生这种情况的原因是因为它可以为你的字符串对象是未分配(没有任何价值)时,他们就行了'tobename使用。 name = namex + namey + namez;'。当您创建作为@DaveDev表明 – Nunners