Unity的C#編程教程_46_遊戲對象的數組挑戰
- 2020 年 9 月 21 日
- AI
- C/C++/C#
- 任務說明:
- 設定一個數組存放 3 個 cube
- 設定一個數組存放 3 種顏色
- 每次按下空格鍵,隨機改變 3 個 cube 的顏色
- 3 個 cube 的顏色保持統一
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ArrayOverview : MonoBehaviour
{
public GameObject[] cubes; // 初始化一個遊戲對象的數組,用於存放方塊對象
public Color[] cubeColors = new Color[] { Color.red, Color.blue, Color.yellow };
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyUp(KeyCode.Space)) // 按下空格鍵
{
int colorID = Random.Range(0, cubeColors.Length);
// 隨機顏色
for (int i = 0; i<cubes.Length; i++)
{
cubes[i].GetComponent<MeshRenderer>().material.color = cubeColors[colorID];
// 遍歷 cube 設定為統一的顏色
}
}
}
}