c# - 销毁不销毁GameObject

标签 c# unity3d destroy

我在 Unity3D 中有以下代码用于添加和删除 3D 绘图的线段:

public class LinearPiecewiseTrajectory : MonoBehaviuor
{
    private List<LineSegment> lineSegmentRep;

    //other stuff here

    public void addSegment()
    {
        GameObject lineSegmentObject = new GameObject();
        lineSegmentObject.name = "LineSegment";

        LineSegment lineSegment = lineSegmentObject.AddComponent<LineSegment>();

        lineSegmentObject.transform.parent = this.transform;
        lineSegmentRep.Add(lineSegment);
    }
}

public void deleteSegment(int i)
{
    Destroy(lineSegmentRep[i]);
}

LineSegment 是我定义的 MonoBehavior。

但是,这个销毁调用实际上并没有销毁 LineSegment 对象。我能发现的唯一可辨别的行为是它将旧 LineSegment 的几何变换设置回身份。

我错过了什么?

最佳答案

However, this destroy call isn't actually destroying the LineSegment object

当您调用 Destroy(componentName); 时,传入的组件将被销毁,但组件所附加的 GameObject 将不会被销毁。

如果您希望 GameObject 销毁所有附加到它的脚本,则应使用 Destroy(componentName.gameObject);

因此将 Destroy(lineSegmentRep[i]); 替换为 Destroy(lineSegmentRep[i].gameObject);

此外,在销毁每个 LineSegment 之前,重要的是您还要将它们从列表中删除,这样您就不会在 lineSegmentRep 列表中有一个空/空的 LineSegment。

public void deleteSegment(int i)
{
    //Remove from the List
    lineSegmentRep.Remove(lineSegmentRep[i]);
    //Now, destroy its object+script
    Destroy(lineSegmentRep[i].gameObject);
}

关于c# - 销毁不销毁GameObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44990156/

相关文章:

c# - 通过 SyncVar 进行 Unity Networking 同步

c# - 在 Unity 中从 Quaternion 和 Vector3 获取新位置

ruby-on-rails - 无法销毁多对多关系中的记录

javascript - 如何彻底销毁一个 JavaScript 对象?

c# - 使用 ajax 渲染局部 View

c# - 使用 XmlReader 读取属性值

c# - 智能 ASCII 字符串表示

c# - 为什么 FileSavePicker 不替换文件?

git - 为什么忽略的文件没有被忽略?

unity3d - Unity 中的 audio.Play() 和 Destroy (gameObject) 计时问题