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?
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.
To achieve this, simply put Destroy(gameObject) in the Update method. This answer is exactly the same as more well recieved answers.
If obj is a GameObject, it destroys the GameObject, all its components and all transform children of the GameObject.
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);
}
it is destroying the component of type LineSegment.
You need to tell to destroy the game object.
Destroy(lineSegmentRep[i].gameObject);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With