按标签查找 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.)
}