如何禁用子组件的MeshRenderer?

huangapple go评论76阅读模式
英文:

How to disable MeshRenderer of child component?

问题

我是新手的unity脚本编写,试图禁用包含collider的子对象的MeshRenderer组件。

using UnityEngine;
using UnityEditor;

// 为每个包含“collider”名称的游戏对象添加一个网格碰撞器
public class Example : AssetPostprocessor
{
    void OnPostprocessModel(GameObject obj)
    {
        Apply(obj.transform);
    }

    void Apply(Transform obj)
    {
        if (obj.name.ToLower().Contains("collider"))
            obj.gameObject.AddComponent<MeshCollider>();

        foreach (Transform child in obj)
            child.GetComponent<MeshRenderer>().enabled = false;
            Apply(child);
    }
}

出现以下错误:

Assets\Editor\CustomImporter.cs(20,13): error CS0103: The name 'child' does not exist in the current context

英文:

I am new to unity scripting and trying to disable the MeshRenderer component of child object whose name contains collider

如何禁用子组件的MeshRenderer?

using UnityEngine;
using UnityEditor;

// Adds a mesh collider to each game object that contains collider in its name
public class Example: AssetPostprocessor
{
    void OnPostprocessModel(GameObject obj)
    {
        Apply(obj.transform);
    }

    void Apply(Transform obj)
    {
        if (obj.name.ToLower().Contains(&quot;collider&quot;))
            obj.gameObject.AddComponent&lt;MeshCollider&gt;();

        foreach (Transform child in obj)
            child.GetComponent&lt;MeshRenderer&gt;().enabled = false;
            Apply(child);
    }
}

Getting this error

Assets\Editor\CustomImporter.cs(20,13): error CS0103: The name &#39;child&#39; does not exist in the current context

答案1

得分: 0

看起来你忘记了foreach循环的花括号{}。

尝试:

foreach (Transform child in obj)
{
    child.GetComponent&lt;MeshRenderer&gt;().enabled = false;
    Apply(child);
}
英文:

It looks like you're missing the curly braces {} for the foreach loop

Try:

    foreach (Transform child in obj)
    {
        child.GetComponent&lt;MeshRenderer&gt;().enabled = false;
        Apply(child);
    }

huangapple
  • 本文由 发表于 2023年3月31日 22:00:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/75899416.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定