Unity的C#編程教程_45_遍歷遊戲對象數組進行操作

  • 數組除了用來存儲字元串,數字,還能用來存儲 unity 中的各種對象

比如我們可以把一些 3d 方塊放進一個數組進行管理,按下空格鍵,把所有的方塊都變成紅色:

首先在 unity 中新建 3 個 cube

然後打開 C# 腳本:

public GameObject[] cubes; // 初始化一個遊戲對象的數組,用於存放方塊對象

然後回到 Unity,就可以拖拽的方式把 3 個 Cube 賦值到數組中

賦值完成後,Cubes 數組的 Size 會變成 3

這個時候我們就可以從腳本中操作這 3 個方塊了

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


public class ArrayOverview : MonoBehaviour
{


    public GameObject[] cubes; // 初始化一個遊戲對象的數組,用於存放方塊對象


    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyUp(KeyCode.Space)) // 檢測到按下空格鍵
        {
            foreach(var cube in cubes) // 遍曆數組中的所有 cube
            {
                cube.GetComponent<MeshRenderer>().material.color = Color.red;
                // 遊戲對象 cube 下面的組件 Mesh Renderer
                // 該組件下面的類 material
                // 該類下的屬性 color
                // 將其設定為紅色
            }
        }
    }
}
Tags: