Tutorial UE4: Crear Blueprint Components con C++

Tutorial Componets

UE4 Tutorial: Create Blueprint Components with C++ (English)

Leer en español.

With the new 4.7 update of Unreal Engine you can now create your own component types for your Blueprints and Actors. They are like small snippets of modular code that can be added to any actor in your level.

For example, we could create a «Spinner» component which would make every actor that uses it to spin around.

There are several tutorials about this concept on the Unreal Engine YouTube channel, but all of them approach it with Blueprints. And while Blueprints are really useful, it is also important to know how to create these components with C++. In this tutorial I will show you how to create a simple component in C++ from scratch. Let’s begin.

To follow this tutorial you will need:

  • Unreal Engine 4.7 or higher.
  • Microsoft Visual Studio if you are using Windows (you can use the Express version).
  • Xcode if you are using Mac OS X.

All code used in this tutorial will be found at the bottom of the page.

1. Create a New Project

The first thing we are going to do is create a new project from a C++ template. If you want to use an existing project you can do so even if you used a different template, but for the purposes of this tutorial I’m going to work with a new project.

To create a new project, open Unreal Engine from the Launcher, select the New Project tab and then click the C++ tab. From there select the Basic Code template, make sure «with starter content» is set, name your project whatever you want and press Create Project.

Ventana para crear el proyecto
New Project Window (click to view in full size).

After compiling your project Visual Studio and Unreal Engine Editor will open automatically.

2. Create a C++ Class

Now we are going to create the C++ class that will contain our component’s code. To do that, in the editor, open the File drop-down menu and choose Add Code to Project.

The Choose Parent Class window will now open. To create a component, we can extend from two classes: ActorComponent and SceneComponent. The former only adds scripting logic, while the latter has a 3D position within the owner actor.

In this case we need to extend from ActorComponent. To do so, check the Show All Classes option, select the ActorComponent class and press Next.

ParentClass
Choose Parent Class window.

After that you will be asked to enter a name for the class. I’m going to call it HoverComponent, but you can name it whatever you want.

Click Create Class. After a few seconds Unreal Engine will open Visual Studio for you with a template for the code of our class.

3. Write and Compile C++ Code

Before proceeding, I want to explain what will our component do when finished. This component will make any actor we apply it on to move up and down smoothly like if it were hovering in the air. To achieve that effect, we will apply a sine function to the time the game has been running each game tick, and add it to the Location vector of the actor.

Keep in mind that the code in the tick function will be executed each frame of the game. Adding slow code to this function will cause FPS to drop drastically.

The first thing we need is a variable to store the time the game has been running. In HoverComponent.h, add the following code just before the closing brace at the end of the file:

float RunningTime;

In HoverComponent.cpp we’ll modify the code of the UHoverComponent::TickComponent() function. We’ll add the following code at the end of the function, just before the last closing brace of the file, without touching the rest of the default code.

First we need to get the location of the actor in the world. If we try to use GetActorLocation()  directly, we will get an error because this actor doesn’t have an actual location in the world. We first need to get the owner actor of this component and store it’s position in a vector. This is the code:

AActor* Owner = GetOwner();
FVector NewLocation = Owner->GetActorLocation();

After that, we calculate the height difference we want to apply to the actor and add it to the Z component of the NewLocation vector. Then we update RunningTime adding the elapsed time to it:

float DeltaHeight = (FMath::Sin(RunningTime + DeltaTime) - FMath::Sin(RunningTime));

NewLocation.Z += DeltaHeight * 20.0f;
RunningTime += DeltaTime;

Finally, we assign the new location vector to the actor so it moves:

Owner->SetActorLocation(NewLocation);

Now that we’re done coding, we can compile it. We can do so from Visual Studio or pressing the Compile button in the Unreal Editor. I recommend you to compile from Visual Studio as it’s faster to read the console log in case you get an error.

To compile from Visual Studio, right click your project in the Solution Explorer and select Build.

Compilar en Visual Studio.
Building in Visual Studio.

If there are no errors, Unreal Engine will automatically load the changes.

4. Test your code

Finally it’s time to see our code in action, but first we need an object to test it on.

Drag and drop a cube or any other object from the left panel to the scene and place it floating in the middle of the air.

cubo

It is really important to set the actor as Movable in the Details Panel to the right, otherwise it won’t be able to move.

Panel de detalles.
Details Panel.

If you play the game now, you’ll see that the cube stays in place without moving, as expected. Now we’ll add our component to it.

In the Content Browser, expand the folder called «C++ Classes«. Within that folder, there is another folder with the name of your project. Select it. On the right you should see the component we just created.

Content Browser.
Content Browser.

Select the cube you created before and drag the component to the components section of the Details Panel.

Añadir componente
Add component.

And that’s it, it’s that simple. If you followed all the steps correctly, when runnig the game the cube should start moving up and down like if it were floating in the air.

Now, for more fun, you can select the elements at the back of the scene (the table and the chairs), set them as movable actors, and add a HoverComponent to each one of them. If you run the game you should see all the actors moving up and down.

As you can see, adding this functionality to any object is fairly simple. That’s the power of componets.

I will leave below the finished code used in this tutorial. If you have any doubts, corrections or suggestions you can leave them in the comments below. I’d like to see what you can do with this concept!

Complete Code

HoverComponent.h

// Copyright 2015 Karma Software, Diego Iáñez.

#pragma once

#include "Components/ActorComponent.h"
#include "HoverComponent.generated.h"

UCLASS( ClassGroup=(Custom), meta=(BlueprintSpawnableComponent) )
class COMPONENTTUTORIAL_API UHoverComponent : public UActorComponent
{
GENERATED_BODY()

public:
// Sets default values for this component's properties
UHoverComponent();

// Called when the game starts
virtual void InitializeComponent() override;

// Called every frame
virtual void TickComponent( float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction ) override;

float RunningTime;
};

HoverComponent.cpp

// Copyright 2015 Karma Software, Diego Iáñez.

#include "ComponentTutorial.h"
#include "HoverComponent.h"

// Sets default values for this component's properties
UHoverComponent::UHoverComponent()
{
// Set this component to be initialized when the game starts, and to be ticked every frame. You can turn these features
// off to improve performance if you don't need them.
bWantsInitializeComponent = true;
PrimaryComponentTick.bCanEverTick = true;

// ...
}

// Called when the game starts
void UHoverComponent::InitializeComponent()
{
Super::InitializeComponent();

// ...

}

// Called every frame
void UHoverComponent::TickComponent( float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction )
{
Super::TickComponent( DeltaTime, TickType, ThisTickFunction );

AActor* Owner = GetOwner();
FVector NewLocation = Owner->GetActorLocation();

float DeltaHeight = (FMath::Sin(RunningTime + DeltaTime) - FMath::Sin(RunningTime));

NewLocation.Z += DeltaHeight * 20.0f;
RunningTime += DeltaTime;

Owner->SetActorLocation(NewLocation);
}

The code in this tutorial is based on this tutorial from UE4 documentation, modified to work as a blueprint component.

Un comentario sobre “Tutorial UE4: Crear Blueprint Components con C++

Deja un comentario