Passing a type as a parameter?

Hi all,

I have this function implemented in blueprints, but I wondered how it can be accomplished in C++.

I am particularly interested in passing the desired class type for spawning.

Any suggestion?

Just to make things clear: you want to pass a class object, or the class itself? If its the former, well then its a basic function, in case its the latter, I recommend Templates.

  1. Place the following code in the header file of a class in which you will call SpawnActor function


//Your class reference
TSubclassOf<class ABaseClass> YourClass;


  1. Use SpawnActor function to spawn the actor of YourClass


void AMyClass::SomeMethod()
{
      if(YourClass)
      {
              GetWorld()->SpawnActor<AYourClass>(YourClass, LOCATION, ROTATION); //There are more overloads of this function
      }
}


SpawnActor function documentation: https://docs.unrealengine.com/latest/INT/API/Runtime/Engine/Engine/UWorld/SpawnActor/4/index.html
Look here for more overloads: https://docs.unrealengine.com/latest/INT/API/Runtime/Engine/Engine/UWorld/index.html

It’s the latter.

I was left with the impression that templates do not work with unreal classes for some reason, but I will investigate this option again, thanks.

Thanks, Ogniok.

I will try it and write back if I have more questions.

I think I’ve managed to get it working.

Thanks a lot!

Here is what I did, just in case someone needs it:



void AMyClass::SpawnAnotherC(TSubclassOf<class AAnotherC> AnotherClass)
{
	if (AnotherClass)
	{
		GetWorld()->SpawnActor<AAnotherC>(AnotherClass, GetActorLocation(), FRotator(0, 0, 0)));
	}
}

2 Likes