为了账号安全,请及时绑定邮箱和手机立即绑定

如何修复 Unity 中的数组索引超出范围错误?

如何修复 Unity 中的数组索引超出范围错误?

C#
SMILET 2021-12-05 17:08:46
我正在 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 initializationvoid Start () {}// Update is called once per framevoid 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;}所以重申:我按向右箭头键一次一个地浏览图像数组。到达数组的末尾后,我再按一次向右箭头键,然后我将被带到项目中的下一个场景。但是,一旦我进入下一个场景,我就无法返回上一个场景,因为“数组索引超出范围”错误 - 我的 LoadPreviousScene() 方法没有被调用。当我在数组的第一个索引上时,我希望能够混合左箭头键并被扔回前一个场景。
查看完整描述

1 回答

?
江户川乱折腾

TA贡献1851条经验 获得超5个赞

问题是由于这种情况:


else if (Input.GetKeyDown(KeyCode.LeftArrow) && currentImageIndex <= nextImage.Length)

当你这样做时,newImage = nextImage[currentImageIndex - 1];你需要确保它currentImageIndex大于 0。


以下是我将如何编写您的方法:


private Image GetNextImage()

{

    if (Input.GetKeyDown(KeyCode.RightArrow))

    {

        if(currentImageIndex < nextImage.Length)

        {

            newImage = nextImage[currentImageIndex++];

            newImage.enabled = true;

        } 

        else

        {

            LoadNextScene();

        }

    }

    else if (Input.GetKeyDown(KeyCode.LeftArrow))

    {

        if(currentImageIndex > 0)

        {

            newImage = nextImage[currentImageIndex--];  

            newImage.enabled = false;                     

        }

        else

        {

            LoadPreviousScene();

        }

    } 

    return newImage;

}

注意我已经将键和索引之间的条件分开了,因为两次测试相同的条件没有多大意义。


查看完整回答
反对 回复 2021-12-05
  • 1 回答
  • 0 关注
  • 838 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信