按標籤查詢 GameObjects

標籤使得定位特定遊戲物件變得特別容易。我們可以尋找單個遊戲物件,或尋找多個。

尋找一個單一的 GameObject

我們可以使用靜態函式 GameObject.FindGameObjectWithTag(string tag) 來查詢單個遊戲物件。重要的是要注意,以這種方式,不以任何特定順序查詢遊戲物件。如果搜尋在場景中的多個遊戲物件上使用的標記,則此函式將無法保證返回哪個遊戲物件。因此,當我們知道只有一個遊戲物件使用這樣的標記時,或者當我們不擔心返回的 GameObject 的確切例項時,它更合適。

///<summary>We create a static string to allow us consistency.</summary>
string playerTag = "Player"

///<summary>We can now use the tag to reference our player GameObject.</summary>
GameObject player = GameObject.FindGameObjectWithTag(playerTag);

查詢 GameObject 例項的陣列

我們可以使用靜態函式 GameObject.FindGameObjectsWithTag(string tag) 來查詢使用特定標記的所有遊戲物件。當我們想要遍歷一組特定的遊戲物件時,這很有用。如果我們想要找到單個遊戲物件,但是可能有多個遊戲物件使用相同的標記,這也很有用。由於我們不能保證 GameObject.FindGameObjectWithTag(string tag) 返回的確切例項,我們必須使用 GameObject.FindGameObjectsWithTag(string tag) 檢索所有潛在的 GameObject 例項的陣列,並進一步分析結果陣列以找到我們正在尋找的例項。

///<summary>We create a static string to allow us consistency.</summary>
string enemyTag = "Enemy";

///<summary>We can now use the tag to create an array of all enemy GameObjects.</summary>
GameObject[] enemies = GameObject.FindGameObjectsWithTag(enemyTag );

// We can now freely iterate through our array of enemies
foreach(GameObject enemy in enemies)
{
    // Do something to each enemy (link up a reference, check for damage, etc.)
}