c# - 我如何创建一种方法来检查游戏对象是否包含特定组件?

标签 c# unity3d

现在我在做:

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/

相关文章:

c# - Unity中有类似Runnable的东西吗?

c# - 在 c# 中使用 unity 在简历上重新启动应用程序

unity3d - XRSettings.enabled 与 Unity 2017.2 和 Oculus 1.18.1

unity3d - 在Unity中选择输出音频设备

unity3d - 在不加入 channel 的情况下在Unity中播放音频效果?

c# - 连续播放 VLC 播放列表中的不同视频文件

c# - 这个对象能够告诉它有多少属性不是空/空白/空有什么问题?

c# - 无法在 C# 控制台应用程序中捕获 Ctrl+C

c# - 为什么在 DataContract 上调用 Dispose,即使服务仍然引用它?

c# - 面板不会停靠在我希望它们在 winforms 中的位置