如何创建一个方法来检查游戏对象是否包含特定组件



现在我正在做:

if (gameObj.GetComponent<MeshRenderer>() == true
&& gameObj.GetComponent<BoxCollider>() == true)
fontColor = meshRendererColor;

但取而代之的是添加&amp;多次为每个组件创建一个方法,您可以获得组件数组,如果游戏对象包含组件,则返回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);

由于要使用字符串,请使用Type.GetType将作为字符串的组件名称转换为Type,然后使用以Type为参数的GetComponent重载。如果组件为false,只需返回false

private static bool IsContainComponents(string[] components, GameObject gameObj)
{
foreach (var cp in components)
{
//Convert the component to Type
Type type = Type.GetType(cp);
//Get component with this component
Component component = gameObj.GetComponent(type);
//If it is null exit the loop then return false
if (component == null)
return false;
}
return true;
}

这应该适用于您自己的组件。如果使用内置的Unity组件,则必须在其前面加上名称空间UnityEngine,然后加上组件名称,再加上逗号和名称空间。

例如,如果您正在寻找一个内置组件Rigidbody,那么它将是"UnityEngine.Rigidbody, UnityEngine"而不是"Rigidbody"

Debug.Log(IsContainComponents(new string[] {"UnityEngine.Rigidbody, UnityEngine" }, gameObject));

您也可以通过使用Component而不是string来解决此问题。

private static bool IsContainComponents(Component[] components, GameObject gameObj)
{
foreach (var cp in components)
{
//Get component with this component
Component component = gameObj.GetComponent(cp.GetType().Name);
//If it is null exit the loop then return false
if (component == null)
return false;
}
return true;
}

最新更新