Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destroy not destroying GameObject

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?

like image 578
user650261 Avatar asked Jul 08 '17 19:07

user650261


People also ask

How do you not destroy an object in unity?

Create a single script called DontDestroy and attach it to every game object you don't want to destroy. Whenever you attach that script to an object, it won't be destroyed.

How do you destroy don't destroy on load?

To achieve this, simply put Destroy(gameObject) in the Update method. This answer is exactly the same as more well recieved answers.

Does destroying GameObject destroy children?

If obj is a GameObject, it destroys the GameObject, all its components and all transform children of the GameObject.


2 Answers

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);
}
like image 100
Programmer Avatar answered Sep 21 '22 07:09

Programmer


it is destroying the component of type LineSegment.

You need to tell to destroy the game object.

Destroy(lineSegmentRep[i].gameObject);
like image 20
Everts Avatar answered Sep 24 '22 07:09

Everts