How do you instantiate things in Unreal Engine?

I require a second PlayerController…

I realised you cannot do


APlayerController* controller = new APlayerController();

How do you go about instantiating things?

I’ve tried this but it throws an error:


NewObject<APlayerController>(APlayerController::StaticClass());

and this:


ConstructObject<APlayerController>(APlayerController::StaticClass());


Fatal error: [File:D:\BuildFarm\buildmachine_++depot+UE4-Releases+4.6\Engine\Source\Runtime\CoreUObject\Private\Templates\Casts.cpp] [Line: 11] 
Cast of Class /Script/TemplatePlatformer.APlayerController to Level failed
UE4Editor.exe has triggered a breakpoint.

UE4Editor.exe has triggered a breakpoint.

This is an article about spawning actors:

I don’t have the code in front of me but spawning components and other UObjects uses ConstructObject. I think the Unreal Tournament source code has a lot of examples of doing this. One thing to keep in mind with spawning components is you still have to register the component manually I think after it’s spawned, otherwise you won’t see the static mesh in the world or whatever it is you spawned.

Thanks, I hadn’t realised it was based off of an actor too. Nice one.

Every class starting with “A” prefix is related to Actor

This doesn’t seem like a problem with construction as much as what you’re doing with it afterwards.

For starters, you shouldn’t have to manually create a player controller, the level startup takes care of that for you.

What if you want 4 local players… I need 4 Player Controllers… Don’t I?.. Each with their own Input Components…

Yes. But there’s a lot more to adding a new controller than just creating the object… There’s a bunch of registration and management happening behind the scenes as well as many related classes.

The default, single controller behaviour has suited us fine for now so I don’t know a lot about how multiple controllers would be done, but I know it should likely be in AGameMode. Look at AGameMode::Login and AGameMode::InitNewPlayer in particular and where those are being called. It looks like UGameInstance::CreateLocalPlayer calls those as needed and would probably be your best starting point.