What's the right way to set a component UPROPERTY?

Not sure there’s a way to directly set a variable with a component. I’ve never been able to do that. If you’re in a BP, you already have FMJCamera. No need for a variable. If you want to access it from C++, this is what I’m using:

void AMyCharacter::PostInitializeComponents()
{
  Super::PostInitializeComponents();

  TArray<UCameraComponent*> Cameras;
  this->GetComponents<UCameraComponent>(Cameras, true);

  check(!Cameras.IsEmpty());
  this->MyCamera = Camera[0];
}

If you need a specific instance, you can iterate over them and check the name with Cameras[i]->GetName(Name).

Note I’m using PostInitializeComponents() because when I packaged my game as standalone, I found out that construction scripts in BP and OnConstruction() in C++ only get called when spawned. If the actor is already in the level when the level gets loaded, construction scripts and OnConstruction() do not get called in a standalone package. In the editor, it always seems to get called.

IMPORTANT: Use BeginPlay event instead of Construction Script unless you know that the actor won’t be in the level when it is loaded.

1 Like