Destroy not destroying GameObject
Asked Answered
T

2

9

I have the following code in Unity3D for adding and deleting a line segment for a 3D drawing:

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 is a MonoBehavior I have defined.

However, this destroy call isn't actually destroying the LineSegment object. The only discernible behavior I can find is that it's setting the old LineSegment's geometric transform back to identity.

What am I missing?

Topic answered 8/7, 2017 at 19:45 Comment(0)
A
16

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

When you call Destroy(componentName);, the component that is passed in will be destroyed but the GameObject the component is attached to will not be destroyed.

If you want the GameObject to destroy with all the scripts attached to it then Destroy(componentName.gameObject); should be used.

So replace Destroy(lineSegmentRep[i]); with Destroy(lineSegmentRep[i].gameObject);.

Also before destroying each LineSegment, it is important that you also remove them from the List so that you won't have an empty/null LineSegment in that lineSegmentRep List.

public void deleteSegment(int i)
{
    //Remove from the List
    lineSegmentRep.Remove(lineSegmentRep[i]);
    //Now, destroy its object+script
    Destroy(lineSegmentRep[i].gameObject);
}
Attis answered 8/7, 2017 at 20:48 Comment(0)
B
5

it is destroying the component of type LineSegment.

You need to tell to destroy the game object.

Destroy(lineSegmentRep[i].gameObject);
Buttercup answered 8/7, 2017 at 20:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.