回顾一下之前在Unity中 做过的跑马灯效果, 利用Sphere[] 数组遍历动态添加颜色,
查找到一点小 bug
1.采用数组, 在Unity 中Sphere 的顺序有所限定
2.需要按照限定的顺序排列Sphere 而不是通过脚本顺序动态添加颜色
故在此采用 List 列表, 具体步骤如下:
Unity 中Sphere 的排列顺序
游戏视图:
具体代码如下:
public class qiuChange : MonoBehaviour {
//List 中存放物体
private List<GameObject> list;
//颜色数组
private Color[] se;
// Use this for initialization
void Start () {
list = new List<GameObject>(); //List 初始化
for (int i = 0; i < 6; i++)
{
list.Add(GameObject.Find("Sphere" + i)); //查找到Unity中所有的Sphere 添加到 list 中
}
//颜色数组
se = new Color[] { Color.black, Color.blue, Color.green, Color.red, Color.yellow, Color.white };
// 利用协程开启颜色调试
StartCoroutine("ChangeColor");
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown(KeyCode.Q)) {
StopCoroutine("ChangeColor");
}
if (Input.GetKeyDown(KeyCode.W))
{
StartCoroutine("ChangeColor");
}
}
IEnumerator ChangeColor()
{
int j = 0;
while (true)
{
for (int i = 0; i < se.Length; i++)
{
list[i].GetComponent<MeshRenderer>().material.color = se[(i + j) % 6];
}
// 等待时间 , 自由设定
yield return new WaitForSeconds(1);
j++;
}
}
}
在这里总结一下需要注意的事项: (仅是个人见解, 如有不足之处, 希望能够得到大家的批评和指点)
1.声明List 需要new 一下 (初始化)列表
2.对List 中添加数据采用 list.add()
3.遍历的时候注意索引的最大值限定
(Index out of range !) 这个问题不容忽视呦
那么 , 最后你就能做出自己想要的效果喽
![在这里插入图片描述](https://img-blog.csdnimg.cn/20181107224515506.PNG)