在Unity的編程中有會使用到查找物體這裏總結一下幾種查找物體的方式:
- 按名稱
- 按標籤
- 按類型(掛載組件)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class FindObj : MonoBehaviour
{
void Start()
{
print("按名稱: " + GameObject.Find("name--01").name);
//查找到結果爲單個物體
print("按標籤(單個): " + GameObject.FindGameObjectWithTag("tag").name);
//查找到結果爲所有符合的物體返回數組
GameObject[] Objs;
Objs = GameObject.FindGameObjectsWithTag("tag");
for (int i = 0; i < Objs.Length; i++)
{
print("按標籤(多個): " + Objs[i].name);
}
//查找到結果爲所有符合的物體返回單個數據
Button findObj = (Button)GameObject.FindObjectOfType(typeof(Button));
print("按類型查找(單個): " + findObj.name);
//查找到結果爲所有符合的物體返回數組
Button[] findObjs = (Button[])GameObject.FindObjectsOfType(typeof(Button));
for (int i = 0; i < findObjs.Length; i++)
{
print("按類型查找(多個): " + findObjs[i].name);
}
}
}