0
\$\begingroup\$

In Unity I frequently find myself doing this in C#:

GameObject myObject = new GameObject();
try{
// do something with that object
}
finally{
   Destroy(myObject);
}

A good example is creating a temporary pivot point for another object. I create the object, parent whatever object I want to rotate, do the rotation, then destroy the object. It's in a finally block so in case anything goes wrong it still destroys the object.

Does Unity have any elegant way to do this? Writing this all the time is tedious, and it's easy to forget the Destroy method at the end.

\$\endgroup\$
2
\$\begingroup\$

I'd recommend not creating objects you don't intend to keep.

For the particular example of pivoting around a point, you can use the Transform.RotateAround method instead, without a temporary object. And it's even fewer lines of code too!

Other temporary uses of GameObjects should have similar, better alternatives.

Creating GameObjects when you don't need them is expensive, and causes garbage collector allocations which eventually build up and force a GC sweep, making your game hitch or stutter if not managed correctly. So, when in doubt, don't make throwaways - create only what you actually need to persist in your scene.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.