8

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?

George Alexandria
  • 2,841
  • 2
  • 16
  • 24
user650261
  • 2,115
  • 5
  • 24
  • 47

2 Answers2

14

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);
}
Programmer
  • 121,791
  • 22
  • 236
  • 328
  • 2
    Thanks so much for pointing that out! That was originally supposed to be a List of the gameObjects, not a list of the MonoBehavior, I don't now why I did that. Thanks! – user650261 Jul 08 '17 at 21:33
5

it is destroying the component of type LineSegment.

You need to tell to destroy the game object.

Destroy(lineSegmentRep[i].gameObject);
Everts
  • 10,408
  • 2
  • 34
  • 45