【发布时间】:2018-08-20 19:34:13
【问题描述】:
我正在 Unity 中制作幻灯片。我有 2 个场景,每个场景都有一个充满图像的数组。当我按下右箭头键时,我可以遍历数组,沿途显示该索引中的每个图像。一旦到达当前场景中数组的末尾,我还可以通过点击右箭头键移动到项目中的下一个场景。到目前为止,一切都很好。
当我尝试向后浏览幻灯片时,问题就出现了。我可以通过按左箭头键轻松地向后跳转当前场景中数组中的图像,但是当我尝试返回上一个场景时,或者我在数组的开头并按下左箭头键,我遇到错误:
数组索引超出范围
我有点理解计算机在说什么——我正在尝试访问不存在的数组索引,但我对如何解决问题持空白。
代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class LoadImage : MonoBehaviour {
[SerializeField] private Image newImage;
[SerializeField] Image[] nextImage;
int currentImageIndex = 0;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
GetNextImage();
}
private Image GetNextImage()
{
if (Input.GetKeyDown(KeyCode.RightArrow) && currentImageIndex < nextImage.Length)
{
newImage = nextImage[currentImageIndex];
newImage.enabled = true;
currentImageIndex++;
}
else if (Input.GetKeyDown(KeyCode.RightArrow) && currentImageIndex == nextImage.Length)
{
LoadNextScene();
}
else if (Input.GetKeyDown(KeyCode.LeftArrow) && currentImageIndex <= nextImage.Length)
{
Debug.Log("poop.");
newImage = nextImage[currentImageIndex - 1]; //<--- I think this is
newImage.enabled = false; // the problem
// child.
currentImageIndex--;
}
else if (Input.GetKeyDown(KeyCode.LeftArrow) && currentImageIndex == nextImage.Length - nextImage.Length)
{
LoadPreviousScene();
}
return newImage;
}
private void LoadNextScene()
{
int currentSceneIndex = SceneManager.GetActiveScene().buildIndex;
SceneManager.LoadScene(currentSceneIndex + 1);
}
private void LoadPreviousScene()
{
int currentSceneIndex = SceneManager.GetActiveScene().buildIndex;
SceneManager.LoadScene(currentSceneIndex - 1);
}
}
所以重申一下:我一次按向右箭头键在图像数组中移动。一旦我到达数组的末尾,我再次按下右箭头键,我将被带到我项目中的下一个场景。但是,一旦我进入下一个场景,我就无法回到上一个场景,因为“数组索引超出范围”错误 - 我的 LoadPreviousScene() 方法不会被调用。
当我在数组的第一个索引上时,我希望能够混合左箭头键并被扔回前一个场景。
【问题讨论】:
-
您需要确保
currentImageIndex - 1没有超出范围,使用if语句。 -
如果
currentImageIndex == 0那么newImage = nextImage[currentImageIndex - 1];将超出范围:nextImage[-1] -
nextImage有一个.Length属性。这将准确地告诉您数组中有多少元素。例如,如果您的数组有 10 个元素,并且您访问10索引,它将超出范围。在 C# 中,索引是从 0 开始的,因此 10 元素数组的索引范围是 0-9。正如@DmitryBychenko 指出的那样,您正在尝试访问永远无效的-1索引。目前尚不清楚您希望代码最终做什么,但您应该肯定会做的一件事是在访问索引之前检查长度