C# 如何检查游戏对象是否包含网格渲染器,但不包含任何碰撞器,然后向其添加碰撞器?

C# 如何检查游戏对象是否包含网格渲染器,但不包含任何碰撞器,然后向其添加碰撞器?,c#,unity3d,C#,Unity3d,我看到列表中的游戏对象objectsToAddCollider在Collider中显示此消息: collider=System.NotSupportedException:已弃用collider属性 您可以使用Collider,因为它是所有碰撞器的基类 AddDescendantsWithTag(transform, objectsToAddCollider); private void addgroundantswithtag(转换父对象,列表) { foreach(在父对象中转换子对象)

我看到列表中的游戏对象objectsToAddCollider在Collider中显示此消息:

collider=System.NotSupportedException:已弃用collider属性


您可以使用Collider,因为它是所有碰撞器的基类

AddDescendantsWithTag(transform, objectsToAddCollider);
private void addgroundantswithtag(转换父对象,列表)
{
foreach(在父对象中转换子对象)
{
if(child.gameObject.GetComponent()!=null
&&child.gameObject.GetComponent()//您可以根据需要修改此行。
{
list.Add(child.gameObject);
}
AddDegeneratsWithTag(子级,列表);
}
}
在2019.1.0版中被弃用并删除

您不能再使用它进行调试


要检查是否有任何类型的
碰撞器
,请使用

    private void AddDescendantsWithTag(Transform parent, List<GameObject> list)
{
    foreach (Transform child in parent)
    {
        if (child.gameObject.GetComponent<MeshRenderer>() != null
            && child.gameObject.GetComponent<Collider>()) // You can modify this line according to your requirement. 
        {
            list.Add(child.gameObject);
        }
        AddDescendantsWithTag(child, list);
    }
}
甚至稍微短一点

Collider collider = child.GetComponent<Collider>() ? collider : child.gameObject.AddComponent<Collider>();
Collider-Collider=child.GetComponent()??child.gameObject.AddComponent();


注意:在智能手机上打印,因此没有保修,但我希望这一想法能够得到明确。

根据unity文档,它在2019年仍然存在。x@akaBase不!仔细阅读API:使用
gameObject。collider
已被删除,使用
GetComponent()
是最好的选择。@derHugo my bad,不习惯在标题中说它过时了,然后显示另一个受支持的方法,而不参考除代码本身以外的方法更改。但是如果我这样做(child.GetComponent())我正在检查是否有碰撞器,但如果没有碰撞器,它将不会进入内部。我想检查具有网格渲染器但没有任何碰撞器的对象,然后向其添加碰撞器。if(child.GetComponent())的意思不是类似于if(child.GetComponent()==true)行中出现错误:var collider=child.GetComponent()?collider:child.gameObject.AddComponent();在碰撞器上?严重性代码描述项目文件行抑制状态错误CS0841在声明之前不能使用局部变量“collider”这就是我再次说的原因…第二个if块仅用于调试成功后的情况。我建议使用一行代码来执行检查和添加一行。是的,很抱歉。对于一行,您必须显式定义类型。您不能在那里使用
var
    private void AddDescendantsWithTag(Transform parent, List<GameObject> list)
{
    foreach (Transform child in parent)
    {
        if (child.gameObject.GetComponent<MeshRenderer>() != null
            && child.gameObject.GetComponent<Collider>()) // You can modify this line according to your requirement. 
        {
            list.Add(child.gameObject);
        }
        AddDescendantsWithTag(child, list);
    }
}
var collider = child.GetComponent<Collider>();
if(child.GetComponent<Collider>())
{
    Debug.Log("Collider found");
}
Collider collider = child.GetComponent<Collider>() ? collider : child.gameObject.AddComponent<Collider>();
Collider collider = child.GetComponent<Collider>() ?? child.gameObject.AddComponent<Collider>();