我实质上是想在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工作空间的一些图像:
如您在最后一个图像中看到的,而不是移动到element_1并停留在那里直到再次按下右箭头,它一直迭代直到element_2。
如您所知,我是新手,非常感谢您的帮助。
谢谢。
此刻,您的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++;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句