Unity3D C# - 变量范围

时间:2014-01-23 10:58:46

标签: c# unity3d scope

我正在将我的Unity3D游戏从JS转换为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'

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

2 个答案:

答案 0 :(得分:4)

变化

    string namex;
    string namey;
    string namez;

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

答案 1 :(得分:1)

这是因为与对象的实例变量不同,局部变量没有自动初始化。

示例:

public class Test1
{
    int number; // this gets initialized automatically to zero (0).

    void TestMethod()
    {
        int local; // in C#, you're required to manually initialize it.
    }
}

您可能想检查一下此内容以获取更多说明。 Why compile error "Use of unassigned local variable"?