使用Unity中的GetKeyDown一次显示一个数组中的元素

时间:2018-08-11 20:35:51

标签: c# arrays image unity3d

我实质上是想在Unity 2018中制作幻灯片。我想每次显示新图像,例如,按下右箭头键。我可以通过在每次按下右箭头键时加载一个全新的场景来做到这一点,但是我可能有成千上万个场景(这是一个很长的幻灯片!),我想知道是否没有更优雅的解决方案。我认为最好的方法是通过图像数组和一个简单的for循环移动到数组中的下一个索引。

因此,我创建了一些图像GameObjects和一个将它们放入数组的脚本。我的问题是,每当我按向右箭头键时,实现的for循环就会一直朝着数组末尾的方向射击,因此我只能看到最后一张图像。我希望能够在按右箭头键的同时一张一张地浏览每个图像。

我的代码:

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

public class LoadImage : MonoBehaviour {

[SerializeField] private Image newImage;
[SerializeField] Image[] nextImage;

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
    GetNextImage();
} 

private Image GetNextImage()
{
    if (Input.GetKeyDown(KeyCode.RightArrow))
    {
        for (int i = 0; i < nextImage.Length; i++)
        {
            newImage = nextImage[i];
            newImage.enabled = true;
        }
    }
    return newImage;
}
} 

以下是游戏停止运行时Unity工作空间的一些图像:

The game is stopped

The game is running but I haven't pressed the right arrow key

The game is running and I've pressed the right arrow key

正如您在最后一张图片中看到的,而不是移动到element_1并停留在那里直到我再次按下向右箭头,它一直迭代直到element_2。

如您所知,我是新手,非常感谢您的帮助。

谢谢。

1 个答案:

答案 0 :(得分:1)

此刻,您的for循环始终以0开始,因为i = 0并结束于图像数组的末尾。 但是您不需要循环。 您必须记住当前图像的编号。此示例说明了它如何在一个方向上工作。

    int currentImageIndex = 0;
    private Image GetNextImage()
    {
        if (Input.GetKeyDown(KeyCode.RightArrow) && currentImageIndex < nextImage.Length)
        {
            //Take image on current postion
            newImage = nextImage[currentImageIndex]; 
            newImage.enabled = true;
            //Add one to currentImageIndex 
            currentImageIndex++;
        }
    }