现在我在做:
if (gameObj.GetComponent<MeshRenderer>() == true
&& gameObj.GetComponent<BoxCollider>() == true)
fontColor = meshRendererColor;
而是多次为每个组件添加 && 以创建一个方法,您可以获得组件数组,如果游戏对象包含它们,它将返回 true。
private static bool IsContainComponents(string[] components, GameObject gameObj)
{
bool contain = false;
return contain;
}
最佳答案
GetComponent有一个采用 System.Type
的重载。
所以你的方法可以是:
public static bool HasAllComponents(GameObject gameObject, params System.Type[] types)
{
for (int i = 0; i < types.Length; i++)
{
if (gameObject.GetComponent(types[i]) == null)
return false;
}
return true;
}
请注意 params
关键字,它让您无需手动创建数组即可调用方法:HasAllComponents(gameObject, typeof(MeshRenderer), typeof(BoxCollider), etc);
.
关于c# - 我如何创建一种方法来检查游戏对象是否包含特定组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53055263/