Explicitely Delete a UObject
Hiya, I am wondering what the best way to destroy a UObject (not an actor) created with NewObject is. Afaik only AActors have the Destroy function. I'm afraid to just call "delete" on it, because I feel like NewObject created objects have extra shutdown steps.
What's the recommended way to deal with this?
asked Apr 28 '15 at 05:13 PM in C++ Programming
UObjects are managed by the garbage collector. To create a UObject appropriately, use NewObject(), NewNamedObject() and ConstructObject(). It is possible to configure the way UObjects will be handled by garbage collector at the time of creation with Object Flags enumeration. (If you like to learn more about UObject Instance Creation, you can go here: https://docs.unrealengine.com/latest/INT/Programming/UnrealArchitecture/Objects/Creation/index.html ) This way, you should not call new or delete on UObjects. If UObject is no longer needed, it usually means that there are no references to it (this may, however differ, depending on the context and garbage collection flags used at the moment of UObject creation). In this situation, you can run ForceGarbageCollection() function:
Please note, that calling this method may cause crashes in some situations, particularly when object is already being destroyed by garbage collector or has a value of null.
Also, if you like to learn more about Unreal Object Handling, you can go here: https://docs.unrealengine.com/latest/INT/Programming/UnrealArchitecture/Objects/Optimizations/index.html
Hope this helped! Good luck!
answered Apr 29 '15 at 07:19 AM
"Thanks much. What I'm wanting to know is if there are ways to force destroy a UObject, similar to AActor::Destroy() or ways to ref count a UObject. "
Please note this is not exactly recommended workflow but it works great for me, use at your discretion.
Gleb's answer is extremely effective as well, though it will clear all non-UPROPERTY linked UObjects all at once.
I recommend Gleb's answer unless you find you really need to clear individual UObjects. I've now shared my own personal solution for what your exact inquiry seems to be.
My solution is really only for if you dont want to wait till the next GC pass, and also dont want to trigger GC to run.
I don't recommend deleting UObject's that would not have gotten cleared by GC naturally.
Follow this question
Once you sign in you will be able to subscribe for any updates here