繁体   English   中英

如何在 Unity 中修复 IndexOutOfRangeException

[英]How to fix IndexOutOfRangeException in Unity

我在文件夹截图中有很多图像。 所以这个脚本将在不应用的情况下从文件夹中调用图像。 但问题是,图像只显示一个图像。 我的意思是他们没有 go 到下一张图像,如幻灯片或淡入/淡出。

然后我不断收到此错误消息:

IndexOutOfRangeException: Index was outside the bounds of the array.

它指向这段代码:

ImageHolder[i].GetComponent<RawImage>().texture = thisTexture;

完整代码:

Texture2D thisTexture;
byte[] bytes;
string fileName;

public GameObject[] ImageHolder = new GameObject[1];
    
void Start()
    {
        var imagesToLoad = Directory.GetFiles(Application.dataPath + "/screenshots", "*.png");
        for (int i = 0; i < imagesToLoad.Length; i++)
    
        {
            thisTexture = new Texture2D(100, 100); //NOW INSIDE THE FOR LOOP
            fileName = imagesToLoad[i];
            bytes = File.ReadAllBytes(fileName);
    
            thisTexture.LoadImage(bytes);
            thisTexture.name = fileName;
    
    
            // This line
            ImageHolder[i].GetComponent<RawImage>().texture = thisTexture;
        }
    }
}

这里我附上了output。 我有 4 个RawImage 图像只是显示并卡住。

在此处输入图像描述

更新!! 错误已解决!

我把变量放在图像持有人

由此

*ImageHolder[i].GetComponent<RawImage>().texture = thisTexture;

*ImageHolder[9].GetComponent<RawImage>().texture = thisTexture;

但只显示在 RawImage(9) 并且仍然停留在一张图像上。

据我了解,您在编辑器中使用 GameObjects 填充数组 ImageHolder。 因此,当您初始化该字段时,您可以删除新 GameObject[1] 的不相关且令人困惑的分配。

但是如果你的 ImageHolder 数组比 imagesToLoad 数组短,你应该跳出 for 循环。

或者通过扩展数组并创建新的 ImageHolders GameObject 以不同的方式解释它,在这种情况下您可能想要使用列表。 您可以直接引用 RawImage 并创建一个 Prefab,这样您就可以更轻松地创建和填充您的列表。

而不是打破 for 循环,您可以只调整 imagesToLoad 数组的大小,或者如果您想使用第一个 use.First() 或 select 特定范围。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM