我正在使用 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。知道为什么会这样吗?
非常感谢。