What is TSubClassOf and how can i use it?

Hey Guys and Gals :slight_smile:

So as the title says i want to know what is TSubClassOf and how can I use it. I know what TSubObjectPtr is and how to use it ,(which got replaced in 4.6) I seen lot of people use it, I did do some searches but couldn’t find any thing that I want. A explanation and a possible example will be useful. Thanks guys!

TSubclassOf<> is essentialy wrapper for



UClass*


You use it as pointer to class, but not to instanced object. It will only point to class default object.

TSubclassOf lets you restrict the types that can be assigned to a class property at runtime or compile time.

For instance, suppose you have a pickup class in your game and you want to create a blueprintable pickup spawner for it. If you were to define your pickup spawner this way:



UPROPERTY( Category=Pickup, EditAnywhere, BlueprintReadWrite )
UClass* PickupType;


This would allow you to assign a pickup type to spawn, but it would also let you assign any UObject. In order to avoid that, you use TSubclassOf, like so:



UPROPERTY( Category=Pickup, EditAnywhere, BlueprintReadWrite )
TSubclassOf<AGamePickup> PickupType;


That way, if you try to assign a non-GamePickup class in native code, the compiler will complain. And when editing blueprint defaults or instances, the dropdown menu will only contain subtypes of GamePickup.

It’s a great tool and you should probably be using it whenever you’re dealing with class variables.

5 Likes

Hey thanks cmartel and iniside :), really appreciate it. Now I know what TSubClassOf is.

1 Like