unity 四个图片左右循环切换代码
时间: 2023-10-30 10:07:12 浏览: 79
你可以使用以下代码来实现四个图片左右循环切换:
```
public Image[] images; // 存储四个图片的数组
private int currentIndex = 0; // 当前显示图片的索引
void Start() {
// 初始化,将第一个图片显示
images[currentIndex].gameObject.SetActive(true);
}
void Update() {
if (Input.GetKeyDown(KeyCode.RightArrow)) {
// 切换到下一张图片
images[currentIndex].gameObject.SetActive(false); // 隐藏当前图片
currentIndex = (currentIndex + 1) % images.Length; // 更新当前索引
images[currentIndex].gameObject.SetActive(true); // 显示下一张图片
}
if (Input.GetKeyDown(KeyCode.LeftArrow)) {
// 切换到上一张图片
images[currentIndex].gameObject.SetActive(false); // 隐藏当前图片
currentIndex = (currentIndex - 1 + images.Length) % images.Length; // 更新当前索引
images[currentIndex].gameObject.SetActive(true); // 显示上一张图片
}
}
```
在上述代码中,我们使用了一个 `Image` 类型的数组来存储四个图片,同时使用一个变量 `currentIndex` 来记录当前显示的图片索引。在 `Start` 方法中,我们将第一个图片显示出来。在 `Update` 方法中,我们监听左右箭头的按键事件,当按下右箭头时,我们隐藏当前显示的图片,更新 `currentIndex` 的值为下一张图片的索引,再将下一张图片显示出来;当按下左箭头时,我们同样隐藏当前显示的图片,更新 `currentIndex` 的值为上一张图片的索引,再将上一张图片显示出来。需要注意的是,在计算上一张图片的索引时,我们使用了取模运算符 `%` 来实现循环切换。