【发布时间】:2021-12-22 02:32:43
【问题描述】:
我在文件夹截图中有很多图像。所以这个脚本将在不应用的情况下从文件夹中调用图像。但问题是,图像只显示一个图像。我的意思是他们没有像幻灯片放映或淡入淡出那样转到下一张图片。
然后我不断收到此错误消息:
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;
}
}
}
我在这里附加了输出。我有 4 个RawImage。图像只是显示并卡住。
【问题讨论】:
-
能否请您为您的问题提供更多详细信息(基本代码)。
-
另请注意:代码片段并非用于格式化代码!代码片段是可运行的代码块,用于创建最小、完整且可验证的示例!
-
你初始化一个大小为 1 的数组。您的游戏对象未初始化,如果您的路径包含多个图像,这也会失败,即使游戏对象已初始化。
-
ImageHolder 包含 1 个元素,并且您很可能在 for 循环中循环了超过 1 个项目。所以很明显,imagesToLoad.Length > 1,所以当 for 循环到达第二个元素 i = 1 时,代码会失败。
-
Noe UnityScript(js) 已经死了,你应该考虑迁移到 C#
标签: c# unity3d indexoutofrangeexception