Spawn an Actor from a TArray of TsubClassOfs

I have a TMap of some integer keys and then a TSubclassOf. The TMap will be randomly populated with about 6 subclasses of ‘TaskBase’ meaning they all are different classes with the same parent. After being populated, they will then be selected in random order and then their individual functions will need to be accessed.

In order to do so, I must be able to spawn an instance of the TSubclassOf. How do I get the type of the specific TSubclassOf and how do I utilize it in the basic GetWorld()->SpawnActor(…) function?



I wrote the following code to automatically spawn appropriately high climbable/ vaultable walls and lights from a JSON file.


You should have similar implementation for a TMap. SoftClassPtr and SubClassOf are similar.

Here is the implementation. Do read the notes.

Hope this helps.

Edit 1: I should add just in case,

  • you might want to opt for a static function which works for multiple classes.
  • The following templated function does that.
  • It is harder to implement in your codebase.
  • but in case anyone looks for it, here it is.

If you want even more control, instead of mentioning class in template, you can just get class with one line of code. But it might be a bad idea because if that class is not included in your calling class, you will have a hard time catching the errors.

Hope this helps moar.

Just implemented something similar and it compiled! I’ll test it when I get home later in the evening and report back. Quick question though. I did try and use the templates previously but was having a ridiculous amount of trouble setting them up with UE4. Is there any good documentation you could recommend? Or is that last snippet you uploaded just a raw CPP class? Thanks again for all the help.

These methods are not documented anywhere. You have to understand the core API and build your way from there. For the same reason, most of such features are not available to blueprint users. The last snippet is a pure C++ header file that statically links to most used functions.