功能启动后,Unity5中的功能更新不会接收变量的值

时间:2015-10-29 00:02:57

标签: c# function unity3d unity5

我正在使用Unity 5.设置如下:

  • 相机。
  • 3D平面和带有3个UI按钮的画布。
  • 附在相机上的c#中的脚本。这样的脚本只包含2个函数: Start()和Update()。

这是脚本:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class ChangeButtonsText : MonoBehaviour {

    public GameObject Menu;

    private Transform[] transforms;
    private List<string> texts;
    private int numButtons;
    private int menuIndex;

    // Use this for initialization
    void Start () {
        texts = new List<string> ();
        for (int i = 0; i < 10; i++) {
            texts.Add("I am the button number " + i.ToString());
        }
        int numButtons = Menu.transform.childCount;
        print ("1 numButtons = " + numButtons.ToString ());
        transforms = new Transform[numButtons];
        for (int i = 0; i < numButtons; ++i) {
            transforms[i] = Menu.transform.GetChild(i);
        }
        print ("2 numButtons = " + numButtons.ToString ());

        menuIndex = 0;
        for (int i = 0; i < numButtons; i++) {
            transforms[i].GetComponentInChildren<UnityEngine.UI.Text>().text = texts[menuIndex];
            if((i < numButtons-1) && (menuIndex < texts.Count - 1)) menuIndex++;
        }
        print ("3 numButtons = " + numButtons.ToString ());


    }

    // Update is called once per frame
    void Update () {
        print ("4 numButtons = " + numButtons.ToString ());

        if(Input.GetKeyDown(KeyCode.Q)) {
            print ("5 numButtons = " + numButtons.ToString ());

            if (menuIndex < texts.Count - 1) menuIndex++;
            print (menuIndex.ToString());
            int j = 0;
            print ("6 numButtons = " + numButtons.ToString ());
            print ("Going in!");
            for (int i = 0; i < numButtons; i++) {
                print ("I'm in!");
                transforms[i].GetComponentInChildren<UnityEngine.UI.Text>().text = texts[menuIndex-j];
                print ("Changed!");
                j++;
            }
        }
    }
}

关于numButtons的3次打印显示3.但是,第4次打印(Update()函数中的第一次打印输出0。 知道为什么会这样吗?

非常感谢。

1 个答案:

答案 0 :(得分:4)

Start()方法中,您声明了一个名为numButtons的新变量,隐藏了具有相同名称的实例成员。要修复它,只需删除之前的int,然后它将分配成员而不是本地变量:

for (int i = 0; i < 10; i++) {
    texts.Add("I am the button number " + i.ToString());
}
numButtons = Menu.transform.childCount; // no "int" here
print ("1 numButtons = " + numButtons.ToString ());