Download

ConstructorHelpers::FClassFinder outside Constructor

I need to find UClass and use it in BeginPlay.
Now I write constructor and save UClass in field:



AMyHUD::APuzzleHUD()
{
	static ConstructorHelpers::FClassFinder<UObject> widgetClass(TEXT("/Game/UI/GameUI.GameUI_C")); // find class by url
	MyUIWidgetClass = *widgetClass.Class; // save to private field
}

void AMyHUD::BeginPlay()
{
	MyUIWidget = CreateWidget<UUserWidget>(GetWorld(), MyUIWidgetClass);
	MyUIWidget->AddToViewport();
	MyUIWidget->SetVisibility(ESlateVisibility::Visible);
}



But I would be more convenient to use FClassFinder in BeginPlay or use as field of class.

  1. Why FClassFinder can’t be use in other methods?
  2. Why if I write it as field of class:


private:
	ConstructorHelpers::FClassFinder<UObject> widgetClass(TEXT("/Game/UI/GameUI.GameUI_C"));


I get error: error C2059: syntax error : ‘string’ ?

  1. I am not sure why exactly FClassFinder is only useable in constructor, but think it’s for performance.
    If you look inside ConstructorHelpers class, you’ll see, that internally it uses StaticLoadClass function.
    You can use it throughr LoadClass:

LoadClass<UObject>(nullptr, TEXT("/Game/UI/GameUI.GameUI_C"));

  1. This is not valid C++ code, because it is not allowed to initialize variables in header. The line you wrote is similar to this:

ConstructorHelpers::FClassFinder<UObject> widgetClass = ConstructorHelpers::FClassFinder<UObject>(TEXT("/Game/UI/GameUI.GameUI_C"));

If you need to load a UClass* latently (outside constructor), I found this to work:

TSoftClassPtrExample.png

TSoftClassPtrStrings.png

TSoftClassPtrLoad.png

Using the following to load and play a line of dialog on demand. This function is in the PlayerController.



  FString soundCuePath; // you'll need the path to the sound cue

  USoundCue* chatSound = Cast<USoundCue>(StaticLoadObject(USoundCue::StaticClass(), NULL, *soundCuePath));
  if (chatSound)
  {
     ClientPlaySound(chatSound);
  }