【问题标题】:Children's component not being removed if there is only one child如果只有一个孩子,则不会删除孩子的组件
【发布时间】:2019-03-20 19:15:14
【问题描述】:

我已经导入了一些 .obj,它们都有不同数量的孩子,有些有 1 个,有些有更多。在我的游戏中,我可以使用鼠标选择这些 .obj 之一,并在我选择的那个周围放置一个轮廓。

不过,我的取消选择功能似乎无法正常工作。当试图从这些对象之一中删除大纲脚本时,如果该对象只有一个子对象,则不会执行此操作。 2 个孩子似乎每次都能正常工作,但 1 个孩子却不行。肯定会进入子删除循环,我最近对其进行了调试,但它只进入一次,而不是有 2 个子级的对象三次进入循环。

知道这可能是什么问题吗?

        if(selected != null){
            Transform[] ts = selected.GetComponentsInChildren<Transform>();
            foreach (Transform child in ts){
                Destroy(child.gameObject.GetComponent<cakeslice.Outline>());
            }
            Destroy(selected.GetComponent<cakeslice.Outline>());
            selected = null;
        }

【问题讨论】:

    标签: c# unity3d children


    【解决方案1】:

    GetComponentsInChildren 包括 Transform 本身的 Transform 以及嵌套的子代!

    返回 GameObject 或其任何子对象中 Type 类型的所有组件。

    组件的搜索是在子对象上递归进行的,所以它包括子对象的子对象,以此类推。

    还要注意它有一个可选参数bool 是否包括当前不活动或禁用的组件。


    但是为什么你得到Transform 而不是GetComponent&lt;cakeslice.Outline&gt;()&gt;?要销毁所有 cakeslice.Outline&gt;() 实例,只需这样做

    var outlines = selected.GetComponentsInChildren<cakeslice.Outline>(true);
    foreach(var line in outline)
    {
        Destroy(line);
    }
    

    【讨论】:

    • 感谢您的回复,我没有意识到它必须这样使用。我们现在工作得很好。
    猜你喜欢
    • 1970-01-01
    • 2019-02-02
    • 2019-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-02
    相关资源
    最近更新 更多