Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds

Creating Classes

Save for later
  • 17 min read
  • 11 Jul 2016

article-image

In this article by William Sherif and Stephen Whittle, authorsof the book Unreal Engine 4 Scripting with C ++ Cookbook, we will discuss about how to create C++ classes and structs that integrate well with the UE4 Blueprints Editor. These classes are graduated versions of the regular C++ classes, and are called UCLASS.

(For more resources related to this topic, see here.)


A UCLASS is just a C++ class with a whole lot of UE4 macro decoration on top. The macros generate additional C++ header code that enables integration with the UE4 Editor itself.


Using UCLASS is a great practice. The UCLASS macro, if configured correctly, can possibly make your UCLASS Blueprintable. The advantage of making your UCLASS Blueprintable is that it can enable your custom C++ objects to have Blueprints visually-editable properties (UPROPERTY) with handy UI widgets such as text fields, sliders, and model selection boxes. You can also have functions (UFUNCTION) that are callable from within a Blueprints diagram. Both of these are shown in the following images:

creating-classes-img-0

On the left, two UPROPERTY decorated class members (a UTexture reference and an FColor) show up for editing in a C++ class's Blueprint. On the right, a C++ function GetName marked as BlueprintCallable UFUNCTION shows up as callable from a Blueprints diagram.

Code generated by the UCLASS macro will be located in a ClassName.generated.h file, which will be the last #include required in your UCLASS header file, ClassName.h.


The following are the topics that we will cover in this article:

  • Making a UCLASS – Deriving from UObject
  • Creating a user-editable UPROPERTY
  • Accessing a UPROPERTY from Blueprints
  • Specifying a UCLASS as the type of a UPROPERTY
  • Creating a Blueprint from your custom UCLASS

Making a UCLASS – Deriving from UObject


When coding with C++, you can have your own code that compiles and runs as native C++ code, with appropriate calls to new and delete to create and destroy your custom objects. Native C++ code is perfectly acceptable in your UE4 project as long as your new and delete calls are appropriately paired so that no leaks are present in your C++ code.

You can, however, also declare custom C++ classes, which behave like UE4 classes, by declaring your custom C++ objects as UCLASS. UCLASS use UE4's Smart Pointers and memory management routines for allocation and deallocation according to Smart Pointer rules, can be loaded and read by the UE4 Editor, and can optionally be accessed from Blueprints.

Note that when you use the UCLASS macro, your UCLASS object's creation and destruction must be completely managed by UE4: you must use ConstructObject to create an instance of your object (not the C++ native keyword new), and call UObject::ConditionalBeginDestroy() to destroy the object (not the C++ native keyword delete).

Getting ready


In this recipe, we will outline how to write a C++ class that uses the UCLASS macro to enable managed memory allocation and deallocation as well as to permit access from the UE4 Editor and Blueprints. You need a UE4 project into which you can add new code to use this recipe.

How to do it...

  1. From your running project, select File | Add C++ Class inside the UE4 Editor.
  2. In the Add C++ Class dialog that appears, go to the upper-right side of the window, and tick the Show All Classes checkbox.
    creating-classes-img-1
  3. Creating a UCLASS by choosing to derive from the Object parent class. UObject is the root of the UE4 hierarchy. You must tick the Show All Classes checkbox in the upper-right corner of this dialog for the Object class to appear in the list view.
  4. Select Object (top of the hierarchy) as the parent class to inherit from, and then click on Next.

    Note that although Object will be written in the dialog box, in your C++ code, the C++ class you will deriving from is actually UObject with a leading uppercased U. This is the naming convention of UE4:

    UCLASS deriving from UObject (on a branch other than Actor) must be named with a leading U.

    UCLASS deriving from Actor must be named with a leading A.

    C++ classes (that are not UCLASS) deriving from nothing do not have a naming convention, but can be named with a leading F (for example, FAssetData), if preferred.

    Direct derivatives of UObject will not be level placeable, even if it contains visual representation elements like UStaticMeshes. If you want to place your object inside a UE4 level, you must at least derive from the Actor class or beneath it in the inheritance hierarchy.

    This article's example code will not be placeable in the level, but you can create and use Blueprints based on the C++ classes that we write in this article in the UE4 Editor.

  5. Name your new Object derivative something appropriate for the object type that you are creating. I call mine UserProfile. This comes off as UUserObject in the naming of the class in the C++ file that UE4 generates to ensure that the UE4 conventions are followed (C++ UCLASS preceded with a leading U).
  6. We will use the C++ object that we've created to store the Name and Email of a user that plays our game. Go to Visual Studio, and ensure your class file has the following form:
    #pragma once
    
    #include "Object.h" // For deriving from UObject
    #include "UserProfile.generated.h" // Generated code
    
    // UCLASS macro options sets this C++ class to be
    // Blueprintable within the UE4 Editor
    UCLASS( Blueprintable )
    class CHAPTER2_API UUserProfile : public UObject
    {
      GENERATED_BODY()
    };

  7. Compile and run your project. You can now use your custom UCLASS object inside Visual Studio, and inside the UE4 Editor. See the following recipes for more details on what you can do with it.

How it works…


UE4 generates and manages a significant amount of code for your custom UCLASS. This code is generated as a result of the use of the UE4 macros such as UPROPERTY, UFUNCTION, and the UCLASS macro itself. The generated code is put into UserProfile.generated.h. You must #include the UCLASSNAME.generated.h file with the UCLASSNAME.h file for compilation to succeed. Without including the UCLASSNAME.generated.h file, compilation would fail. The UCLASSNAME.generated.h file must be included as the last #include in the list of #include in UCLASSNAME.h.





Right Wrong
#pragma once

 

#include "Object.h"

#include "Texture.h"

// CORRECT: .generated.h last file

#include "UserProfile.generated.h"
#pragma once

 

#include "Object.h"

#include "UserProfile.generated.h"

// WRONG: NO INCLUDES AFTER

// .GENERATED.H FILE

#include "Texture.h"


The error that occurs when a UCLASSNAME.generated.h file is not included last in a list of includes is as follows:

>> #include found after .generated.h file - the .generated.h file should always be the last #include in a header

There's more…


There are a bunch of keywords that we want to discuss here, which modify the way a UCLASS behaves. A UCLASS can be marked as follows:

  • Blueprintable: This means that you want to be able to construct a Blueprint from the Class Viewer inside the UE4 Editor (when you right-click, Create Blueprint Class… becomes available). Without the Blueprintable keyword, the Create Blueprint Class… option will not be available for your UCLASS, even if you can find it from within the Class Viewer and right-click on it.
    creating-classes-img-2
  • The Create Blueprint Class… option is only available if you specify Blueprintable in your UCLASS macro definition. If you do not specify Blueprintable, then the resultant UCLASS will not be Blueprintable.
  • BlueprintType:  Using this keyword implies that the UCLASS is usable as a variable from another Blueprint. You can create Blueprint variables from the Variables group in the left-hand panel of any Blueprint's EventGraph. If NotBlueprintType is specified, then you cannot use this Blueprint variable type as a variable in a Blueprints diagram. Right-clicking the UCLASS name in the Class Viewer will not show Create Blueprint Class… in its context menu.
    creating-classes-img-3


Any UCLASS that have BlueprintType specified can be added as variables to your Blueprint class diagram's list of variables.

You may be unsure whether to declare your C++ class as a UCLASS or not. It is really up to you. If you like smart pointers, you may find that UCLASS not only make for safer code, but also make the entire code base more coherent and more consistent.

See also


To add additional programmable UPROPERTY to the Blueprints diagrams, see the section on Creating a user-editable UPROPERTY, further in the article.

Creating a user-editable UPROPERTY


Each UCLASS that you declare can have any number of UPROPERTY declared for it within it. Each UPROPERTY can be a visually editable field, or some Blueprints accessible data member of the UCLASS.

There are a number of qualifiers that we can add to each UPROPERTY, which change the way it behaves from within the UE4 Editor, such as EditAnywhere (screens from which the UPROPERTY can be changed), and BlueprintReadWrite (specifying that Blueprints can both read and write the variable at any time in addition to the C++ code being allowed to do so).

Getting ready


To use this recipe, you should have a C++ project into which you can add C++ code. In addition, you should have completed the preceding recipe, Making a UCLASS – Deriving from UObject.

How to do it...

  1. Add members to your UCLASS declaration as follows:
    UCLASS( Blueprintable )
    class CHAPTER2_API UUserProfile : public UObject
    {
      GENERATED_BODY()
      public:
      UPROPERTY(EditAnywhere, BlueprintReadWrite, Category =   Stats)
      float Armor;
      UPROPERTY(EditAnywhere, BlueprintReadWrite, Category =   Stats)
      float HpMax;
    };

  2. Create a Blueprint of your UObject class derivative, and open the Blueprint in the UE4 editor by double-clicking it from the object browser.
  3. You can now specify values in Blueprints for the default values of these new UPROPERTY fields.
    creating-classes-img-4
  4. Specify per-instance values by dragging and dropping a few instances of the Blueprint class into your level, and editing the values on the object placed (by double-clicking on them).

How it works…


The parameters passed to the UPROPERTY() macro specify a couple of important pieces of information regarding the variable. In the preceding example, we specified the following:

  • EditAnywhere: This means that the UPROPERTY() macro can be edited either directly from the Blueprint, or on each instance of the UClass object as placed in the game level. Contrast this with the following:
    • EditDefaultsOnly: The Blueprint's value is editable, but it is not editable on a per-instance basis
    • EditInstanceOnly: This would allow editing of the UPROPERTY() macro in the game-level instances of the UClass object, and not on the base blueprint itself
    • Unlock access to the largest independent learning library in Tech for FREE!
      Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
      Renews at $19.99/month. Cancel anytime

  • BlueprintReadWrite: This indicates that the property is both readable and writeable from Blueprints diagrams. UPROPERTY() with BlueprintReadWrite must be public members, otherwise compilation will fail. Contrast this with the following:
    • BlueprintReadOnly: The property must be set from C++ and cannot be changed from Blueprints

  • Category: You should always specify a Category for your UPROPERTY(). The Category determines which submenu the UPROPERTY() will appear under in the property editor. All UPROPERTY() specified under Category=Stats will appear in the same Stats area in the Blueprints editor.

See also


A complete UPROPERTY listing is located at https://docs.unrealengine.com/latest/INT/Programming/UnrealArchitecture/Reference/Properties/Specifiers/index.html.

Accessing a UPROPERTY from Blueprints


Accessing a UPROPERTY from Blueprints is fairly simple. The member must be exposed as a UPROPERTY on the member variable that you want to access from your Blueprints diagram. You must qualify the UPROPERTY in your macro declaration as being either BlueprintReadOnly or BlueprintReadWrite to specify whether you want the variable to be either readable (only) from Blueprints, or even writeable from Blueprints.

You can also use the special value BlueprintDefaultsOnly to indicate that you only want the default value (before the game starts) to be editable from the Blueprints editor. BlueprintDefaultsOnly indicates the data member cannot be edited from Blueprints at runtime.

How to do it...

  1. Create some UObject-derivative class, specifying both Blueprintable and BlueprintType, such as the following:
    UCLASS( Blueprintable, BlueprintType )
    class CHAPTER2_API UUserProfile : public UObject
    {
      GENERATED_BODY()
      public:
      UPROPERTY(EditAnywhere, BlueprintReadWrite, Category =   Stats)
      FString Name;
    };
    The BlueprintType declaration in the UCLASS macro is required to use the UCLASS as a type within a Blueprints diagram.

  2. Within the UE4 Editor, derive a Blueprint class from the C++ class, as shown in Creating a Blueprint from your custom UCLASS.
  3. Create an instance of your Blueprint-derived class in the UE4 Editor by dragging an instance from the Content Browser into the main game world area. It should appear as a round white sphere in the game world unless you've specified a model mesh for it.
  4. In a Blueprints diagram which allows function calls (such as the Level Blueprint, accessible via Blueprints | Open Level Blueprint), try printing the Name property of your Warrior instance, as seen in the following screenshot:
    creating-classes-img-5

Navigating Blueprints diagrams is easy. Right-Click + Drag to pan a Blueprints diagram; Alt + Right-Click + Drag to zoom.

How it works…


UPROPERTY are automatically written Get/Set methods for UE4 classes. They must not be declared as private variables within the UCLASS, however. If they are not declared as public or protected members, you will get a compiler error of the form:

>> BlueprintReadWrite should not be used on private members

Specifying a UCLASS as the type of a UPROPERTY


So, you've constructed some custom UCLASS intended for use inside of UE4. But how do you instantiate them? Objects in UE4 are reference-counted and memory-managed, so you should not allocate them directly using the C++ keyword new. Instead, you'll have to use a function called ConstructObject to instantiate your UObject derivative. ConstructObject doesn't just take the C++ class of the object you are creating, it also requires a Blueprint class derivative of the C++ class (a UClass* reference). A UClass* reference is just a pointer to a Blueprint.

How do we instantiate an instance of a particular Blueprint from C++ code? C++ code does not, and should not, know concrete UCLASS names, since these names are created and edited in the UE4 Editor, which you can only access after compilation. We need a way to somehow hand back the Blueprint class name to instantiate to the C++ code.

The way we do this is by having the UE4 programmer select the UClass that the C++ code is to use from a simple dropdown menu listing all the Blueprints available (derived from a particular C++ class) inside the UE4 editor. To do this, we simply have to provide a user-editable UPROPERTY with a TSubclassOf<C++ClassName>-typed variable. Alternatively, you can use FStringClassReference to achieve the same objective.

This makes selecting the UCLASS in the C++ code is exactly like selecting a Texture to use. UCLASS should be considered as resources to the C++ code, and their names should never be hard-coded into the code base.

Getting ready


In your UE4 code, you're often going to need to refer to different UCLASS in the project. For example, say you need to know the UCLASS of the player object so that you can use SpawnObject in your code on it. Specifying a UCLASS from C++ code is extremely awkward, because the C++ code is not supposed to know about the concrete instances of the derived UCLASS that were created in the Blueprints editor at all. Just as we don't want to bake specific asset names into the C++ code, we don't want to hard-code derived Blueprints class names into the C++ code.

So, we use a C++ variable (for example, UClassOfPlayer), and select that from a Blueprints dialog in the UE4 editor. You can do so using a TSubclassOf member or an FStringClassReference member, as shown in the following screenshot:

creating-classes-img-6

How to do it...

  1. Navigate to the C++ class that you'd like to add the UCLASS reference member to. For example, decking out a class derivative with the UCLASS of the player is fairly easy.
  2. From inside a UCLASS, use code of the following form to declare a UPROPERTY that allows selection of a UClass (Blueprint class) that derives from UObject in the hierarchy:
    UCLASS()
    class CHAPTER2_API UUserProfile : public UObject
    {
      UPROPERTY(EditAnywhere, BlueprintReadWrite, Category =   Unit)
      TSubclassOf<UObject> UClassOfPlayer; // Displays any   UClasses
      // deriving from UObject in a dropdown menu in Blueprints
    
      // Displays string names of UCLASSes that derive from
      // the GameMode C++ base class
      UPROPERTY( EditAnywhere, meta=(MetaClass="GameMode"),   Category = Unit )
      FStringClassReference UClassGameMode;
    };

  3. Blueprint the C++ class, and then open that Blueprint. Click on the drop-down menu beside your UClassOfPlayer menu.
  4. Select the appropriate UClassOfPlayer member from the drop-down menu of the listed UClass.

How it works…

TSubclassOf


The TSubclassOf< > member will allow you to specify a UClass name using a drop-down menu inside of the UE4 editor when editing any Blueprints that have TSubclassOf< > members.

FStringClassReference


The MetaClass tag refers to the base C++ class from which you expect the UClassName to derive. This limits the drop-down menu's contents to only the Blueprints derived from that C++ class. You can leave the MetaClass tag out if you wish to display all the Blueprints in the project.

Creating a Blueprint from your custom UCLASS


Blueprinting is just the process of deriving a Blueprint class for your C++ object. Creating Blueprint-derived classes from your UE4 objects allows you to edit the custom UPROPERTY visually inside the editor. This avoids hardcoding any resources into your C++ code. In addition, in order for your C++ class to be placeable within the level, it must be Blueprinted first. But this is only possible if the C++ class underlying the Blueprint is an Actor class-derivative.

There is a way to load resources (like textures) using FStringAssetReferences and StaticLoadObject. These pathways to loading resources (by hardcoding path strings into your C++ code) are generally discouraged, however. Providing an editable value in a UPROPERTY(), and loading from a proper concretely typed asset reference is a much better practice.

Getting ready


You need to have a constructed UCLASS that you'd like to derive a Blueprint class from (see the section on Making a UCLASS – Deriving from UObject given earlier in this article) in order to follow this recipe. You must have also marked your UCLASS as Blueprintable in the UCLASS macro for Blueprinting to be possible inside the engine.

Any UObject-derived class with the meta keyword Blueprintable in the UCLASS macro declaration will be Blueprintable.

How to do it…

  1. To Blueprint your UserProfile class, first ensure that UCLASS has the Blueprintable tag in the UCLASS macro. This should look as follows:
    UCLASS( Blueprintable )
    class CHAPTER2_API UUserProfile : public UObject

  2. Compile and run your code.
  3. Find the UserProfile C++ class in the Class Viewer (Window | Developer Tools | Class Viewer). Since the previously created UCLASS does not derive from Actor, to find your custom UCLASS, you must turn off Filters | Actors Only in the Class Viewer (which is checked by default).
    creating-classes-img-7Turn off the Actors Only check mark to display all the classes in the Class Viewer. If you don't do this, then your custom C++ class may not show!

    Keep in mind that you can use the small search box inside the Class Viewer to easily find the UserProfile class by starting to type it in.
    creating-classes-img-8

  4. Find your UserProfile class in the Class Viewer, right-click on it, and create a Blueprint from it by selecting Create Blueprint…
  5. Name your Blueprint. Some prefer to prefix the Blueprint class name with BP_. You may choose to follow this convention or not, just be sure to be consistent.
  6. Double-click on your new Blueprint as it appears in the Content Browser, and take a look at it. You will be able to edit the Name and Email fields for each UserProfile Blueprint instance you create.

How it works…


Any C++ class you create that has the Blueprintable tag in its UCLASS macro can be Blueprinted within the UE4 editor. A blueprint allows you to customize properties on the C++ class in the visual GUI interface of UE4.

Summary


The UE4 code is, typically, very easy to write and manage once you know the patterns. The code we write to derive from another UCLASS, or to create a UPROPERTY or UFUNCTION is very consistent. This article provides recipes for common UE4 coding tasks revolving around basic UCLASS derivation, property and reference declaration, construction, destruction, and general functionality.

Resources for Article:





Further resources on this subject: