Unity实现跑马灯效果

进入Unity先建立三个floder

  • prefabs
  • Scripts
  • Scenes

建立六个Cube,在建立一个空物体挂载脚本

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


public class paoma : MonoBehaviour
{
    // Use this for initialization
    private GameObject[] _cubes;//定义一个cube数组
    private Color[] _colors;//色块数组
    void Start()
    {
        //实例化色块数组
        _colors = new Color[] { Color.black, Color.blue, Color.green, Color.red, Color.yellow, Color.white };
        //标签带MyCube
        _cubes = GameObject.FindGameObjectsWithTag("MyCube");
        //开启一个协程
        StartCoroutine("changeColorEnumerator");
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Q))
        {
            //关掉协程
            StopCoroutine("changeColorEnumerator");
        }
    }
    //协程
    IEnumerator changeColorEnumerator()
    {
        int j = 0;
        while (true)
        {
            for (int i = 0; i < _colors.Length; i++)
            {
                //_cubes中第i个赋值颜色为                                 _colors的下标I+J除六的余数,j每次增加一
                _cubes[i].GetComponent<MeshRenderer>().material.color = _colors[(i + j) % 6];
            }
            //等待三秒后,J++
            yield return new WaitForSeconds(3);
            j++;
            if (j >= int.MaxValue - 7)//给J一个范围
            {
                j = 0;
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/luxifa1/article/details/82626500