为什么我的for循环无限循环

时间:2015-01-28 14:48:23

标签: for-loop unity3d

我在Unity3D中创建了两个脚本,它们应该检查文件夹中的对象的名称和数量。问题是,它无限地完成了它的工作。你不知道问题出在哪里吗?

第一个脚本

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

public class MenuSetup : MonoBehaviour {


    public static List<Texture2D> UnitIconTextures = new List<Texture2D>();
    public static List<string> UnitNames = new List<string>();
    public static List<string> UnitPaths = new List<string>();


    void OnGUI(){
        for(int i = 0; i < UnitNames.Count; i++){
            Debug.Log (UnitNames[i]);
        }

    }


}

第二个脚本

using UnityEngine;
using System.Collections;

public class World : MonoBehaviour {

    void Start(){
        string path = "Prefabs/Units";  
        Object[] Units = Resources.LoadAll (path);

        if(Units.Length > 0){
            for(int i = 0; i < Units.Length; i++){
                GameObject unit = Units[i] as GameObject;
                Texture2D unitIcon = unit.GetComponent<Unit>().MenuIcon;

                MenuSetup.UnitIconTextures.Add (unitIcon);
                MenuSetup.UnitNames.Add (unit.name);
                MenuSetup.UnitPaths.Add (path+"/"+unit.name);
            }
        }
    }

}

1 个答案:

答案 0 :(得分:1)

确定。没有什么是无限循环的。问题出在这个代码上:

void OnGUI(){
    for(int i = 0; i < UnitNames.Count; i++){
        Debug.Log (UnitNames[i]);
    }

}

此方法每帧可能被称为几次。这就是为什么你会看到很多调试信息的原因。虽然Start方法仅被调用一次。实际上,在World中,Start方法被调用一次。此方法仅将所有信息添加到MenuSetup类一次。然后你在每一帧上调用Debug.Log

unity doc上阅读有关OnGUI的更多信息。另外,您应该阅读Start方法here

小建议

您可能不需要if签入

if(Units.Length > 0){
    for(int i = 0; i < Units.Length; i++){
        GameObject unit = Units[i] as GameObject;
        Texture2D unitIcon = unit.GetComponent<Unit>().MenuIcon;

        MenuSetup.UnitIconTextures.Add (unitIcon);
        MenuSetup.UnitNames.Add (unit.name);
        MenuSetup.UnitPaths.Add (path+"/"+unit.name);
    }
}

因为不会执行Units.Length == 0 for-block。所以可能你想写

for(int i = 0; i < Units.Length; i++){
    GameObject unit = Units[i] as GameObject;
    Texture2D unitIcon = unit.GetComponent<Unit>().MenuIcon;

    MenuSetup.UnitIconTextures.Add (unitIcon);
    MenuSetup.UnitNames.Add (unit.name);
    MenuSetup.UnitPaths.Add (path+"/"+unit.name);
}