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.
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: Creating Objects in Unreal Engine | Unreal Engine 5.1 Documentation ) 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:
GetWorld()->ForceGarbageCollection(true);
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:
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. I have a “system” object kind of like the UAIPerceptionSystem, which should only live in a certain place that controls its lifetime. I’m not sure what would be the best way to implement that.
I’ve noticed it’s come up a couple times where I know an object should be destroyed at a certain point, but I have no way of checking if there’s anything preventing that from happening or forcing the engine to destroy it.
Please note this is not exactly recommended workflow but it works great for me, use at your discretion.
's answer is extremely effective as well, though it will clear all non-UPROPERTY linked UObjects all at once.
I recommend '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.
I have a class that persists across map changes, and the game was crashing when you quit due to this not being properly disposed of. Combined with this other answer, this completely sorted the problem. Thanks!