难点:
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using UnityEngine.UI;
- public class GameManager : MonoBehaviour
- {
- public GameObject[] item;
- public GameObject maskRed;
- public Button Go;
- public int roundCount;//转的圈数(元素一共22个)
- public int steps=-1;
- public float onceTime=0.2f;
- public int index=0;
- public int maskRedIndex = -1;
- public void StartGo()
- {
- RandomSteps();
- StartCoroutine("RunMarquee");
- }
- //随机多少步
- public void RandomSteps()
- {
- roundCount = Random.Range(1,6);
- steps = Random.Range(0,21);
- steps = steps + roundCount*item.Length;
- print(steps);
- }
- IEnumerator RunMarquee()
- {
- for (int i = 0; i < steps; i++)
- {
- index = (index + 1) % item.Length; // 更新当前图片索引
- maskRed.transform.position = item[index].transform.position; // 更新红纸位置
- yield return new WaitForSeconds(onceTime); // 等待一段时间
- }
- }
- }
复制代码
代码分析
index: 当前图片的索引。item.Length: 图片对象数组的长度,即数组中图片的数量。%: 取模运算符,用于计算两个数相除后的余数。
详细解释- index + 1: 每次执行这行代码时,index 的值会增加 1。这意味着每次循环都会指向数组中的下一个元素。
- % item.Length: 取模运算确保 index 的值始终在 0 到 item.Length - 1 之间。当 index 达到 item.Length 时,取模运算会将其重置为 0,从而实现循环效果。
示例假设 item.Length 为 5,即数组中有 5 张图片。初始时 index 为 0。 - 第一次循环:index = (0 + 1) % 5 = 1
- 第二次循环:index = (1 + 1) % 5 = 2
- 第三次循环:index = (2 + 1) % 5 = 3
- 第四次循环:index = (3 + 1) % 5 = 4
- 第五次循环:index = (4 + 1) % 5 = 0
通过这种方式,index 的值会在 0 到 4 之间循环,确保不会超出数组的边界。 结论这行代码的作用是实现一个循环索引,使得 index 在数组 item 的范围内不断循环递增,从而实现走马灯效果。每次循环时,maskRed 的位置会更新为当前图片的位置,形成连续的动画效果。
|