0
\$\begingroup\$
Mesh.Destroy(myGameObject.GetComponent<MeshFilter>());

May it cause any problems or undefined behaviour? (the reason I ask this is that I'm trying to destroy an exiting component which is returned from function.

\$\endgroup\$
1
  • \$\begingroup\$ Do note that in C# there isn't really such a thing as undefined behavior (unless writing unsafe code) and that the worst thing that could possibly happen in this situation is a missing object reference. Before asking what will happen, try do delete it first and then question those results. \$\endgroup\$
    – Zimano
    Nov 5, 2016 at 19:00

1 Answer 1

2
\$\begingroup\$

You're not destroying the mesh. You're using the Destroy method of the Mesh class, which is inherited from the Object class. Then you're calling that on the MeshFilter component of the game object. This doesn't destroy the mesh, it's going to destroy the MeshFilter component from your game object. Destroying in this way will delay the destroy until after the update loop, so, unless you're referencing the meshfilter yourself somewhere else, you won't have any problems.

It's OK to destroy a component in this way, but you can make it more clear with:

Destroy(myGameObject.GetComponent<MeshFilter>());

If you want to destroy the mesh, you'd do something like:

Destroy(myGameObject.GetComponent<MeshFilter>().mesh);

Which should destroy the instantiated mesh for that mesh filter. You'll have to do some testing around this, but I'm fairly sure Unity can handle its mesh being destroyed while still in use by the mesh filter.

\$\endgroup\$
1
  • \$\begingroup\$ This isn't MY code. Thx a lot. \$\endgroup\$
    – Netherwire
    Jun 16, 2014 at 18:06

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .