How can I stop the Garbage Collector from removing a UTexture2D?

I have a C++ class not extending anything, it acts as a wrapper around a library, for use in Unreal Engine 4.

Initially I had the UTexture defined like this:

private:
     UTexture2D *Texture;

However, after creating the texture using CreateTransient, I noticed it got destroyed after 50-60 seconds. ■■■■… the garbage collector is at it.

I ended up fixing this by making it a UProperty, and after initializing the texture, calling AddToRoot.

But I was wondering, is this the only way? How come my initial way doesn’t count as “keeping a reference” even though the wrapper never “dies”?

private:
UPROPERTY()
UTexture2D *Texture;

Is indeed the correct way

Use UPROPERTY to tell the UE4 GC system to leave your texture, or any spawned/ new object asset alone :slight_smile:

Null out the reference when you are ready to have it GC’ed

Texture = nullptr;

#Wiki Tutorial on GC and Dynamic Memory Management

1 Like

Hi.

It’s quite an old post but is relevant to my work. Is it event possible to garbage collect UTexture2D with UPROPERTY by setting them to nullptr?

I was trying to do this. I created new texture using UTexture2D::CreateTransient method. Then, when I didn’t need it anymore I set texture to nullptr.

I was forcing Garbage Collection but it didn’t run the BeginDestroy of UTexture2D.

I know that texture should be removed using ConditionalBeginDestroy() method, but shouldn’t garbage collector work for every UObjects? (For pure UObjects everything works fine). How about other objects that inherits from UObjects? Which can be garbage collected and which not?