如何检测有多少游戏对象拥有某种材质?

Pos*_*rum 6 c# unity-game-engine

所以我目前正在使用c#进行统一的益智游戏.我决定玩家是否获胜的方式是,如果一堆游戏对象拥有相同的材料.如何确定有多少游戏对象附加了某种材料?

Fre*_*erg 1

假设您有某种游戏对象列表,您可以这样做

private int CountMaterials(Material material)
{
    int count = 0;
    foreach (var gameObject in gameObjects)
    {
        if (gameObject.GetComponent<MeshRenderer>().sharedMaterial == material)
           count++;
    }
    return count;
}
Run Code Online (Sandbox Code Playgroud)

并像这样使用它

if(CountMaterials(mat) > CountMaterials(mat2)) 
{
    Debug.Log("1 Wins");
}
else
{
    Debug.Log("2 Wins");
}
Run Code Online (Sandbox Code Playgroud)

编辑:在触发器中分配材质时,请确保使用共享材质而不是材质,因为分配材质会创建材质的新实例。