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 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:
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:
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.
It’s not entirely useless from C++. It’s definitely unfortunate that it doesn’t produce a compiler error in those cases but it’s a surprisingly difficult issue to solve completely. In fact it’s possible to pass in the wrong type of class from blueprint as well without trying too hard.
But what you do get in C++ is that even if the wrong class is passed in, TSubclassOf::Get will return nullptr if the assigned class is wrong. So you can catch it at runtime and check/ensure/log.