2014-01-23 50 views
2

我将我的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' 

我相信是我声明字符串的方式。任何想法如何解决这个问题?

+0

发生这种情况的原因是因为它可以为你的字符串对象是未分配(没有任何价值)时,他们就行了'tobename使用。 name = namex + namey + namez;'。当您创建作为@DaveDev表明 – Nunners

回答

4

变化

string namex; 
    string namey; 
    string namez; 

string namex = string.Empty; 
    string namey = string.Empty; 
    string namez = string.Empty; 
+0

哇只需指定一个空值它们!快速和现货!谢谢!仔细解释一点深入? – sooon

+0

这是因为string'的'的默认值是'null'。有比我更好的人可以解释它。检查此:http://stackoverflow.com/questions/14337551/why-is-the-default-value-of-the-string-type-null-instead-of-an-empty-string。如果答案是正确的,接受它,这和StackOverflow上任何其他的答案,可以帮助您正确的。 – DaveDev

+0

另外@sooon通知在你的代码中没有别的东西来设置这些变量,如果以前的条件都不是真的,那么它们就有可能为空。 –