Component Initializion

Components are initialized just after construction script is run.  Initializion goes through three stages ”Preinitialize”, ”Initialize” and ”PostInitialize”. All functions can be overridden. It is up to programmer to figure out how to use those functions. If you are planning to do something with the components, this is the fool-proof place to do the logic. You can for example create bindings in PostInitialize() so you dont need to do that in BeginPlay().


Example

In this example we are going to create a class based on Actor. We want the class to have a static mesh component that we can be edited inside C++. However, we don’t want to go through the trouble using the Construction Helper or any loaders that requires us to set path to our assets manually. Basically, we want to set the mesh in blueprint, but we want to control it in C++. How we can do that? PostInitializeComponents() function will do exactly that for us!

Let’s start by creating our C++ class and immediadely create a Blueprint based on that class. Then we add Static mesh component and set some mesh for it.

a1

Now. Lets go into our code and create a pointer that points to UStaticMeshComponent. We also create a function for our PostInitializeComponents().

public:
// Sets default values for this actor's properties
AC_PostInitActor();
virtual void PostInitializeComponents() override;

protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
// Our component.
UPROPERTY()
UStaticMeshComponent* MainMesh;

In .CPP we declare the function. In Function we use GetComponents() method to find the all static mesh components this actor holds and set mesh reference to our MainMesh.

void AC_PostInitActor::PostInitializeComponents()
{
Super::PostInitializeComponents();
// Placeholder array
TArray<UStaticMeshComponent*> Components;
this->GetComponents(Components);
// Safe check so editor wont crash if no components was found.
if (Components.Num() > 0)
// set our actual mesh
MainMesh = Components[0];
}

Now, it does not matter if we change mesh in blueprint or in C++, the changes will affect the same mesh. Let’s activate physics for our mesh in C++ BeginPlay()

// Called when the game starts or when spawned
void AC_PostInitActor::BeginPlay()
{
Super::BeginPlay();
MainMesh->SetSimulatePhysics(true);
}

When we start the game. Our Mesh will fall down. This proves that we have full control to one mesh in both blueprints and in C++.

Vastaa

Sähköpostiosoitettasi ei julkaista. Pakolliset kentät on merkitty *