skip to Main Content

Casting types in Unreal Engine

Casting means that you can convert a type to another type. For example, you can convert a given Actor to a AStaticMeshActor in order to access a specific functionality of second one. To do this, you must make use of pointers. This post assumes you are familiar with pointers in c++, if that’s not the case, check out this post.

In this post I’m going to use the FirstPersonBlueprint project (of course you may choose any template you want-you just need a level populated with actors).

Declaring a Pointer in Unreal Engine

After the Unreal Engine loaded the template I chose:

  • I created a C++ class named CActor which inherits from Actor
  • I added a reference to an actual Actor as seen below:

actor_reference

Casting a given Actor during play time

For the next step, I switched to the source file of my class and inside the BeginPlay function I typed in the following code:

The first parameterer of the cast function is the class I want to try to cast to and the second parameter is the actual Actor that I’m going to cast.

Note:When casting, ALWAYS check your pointer as seen in the code above.

Create a Blueprint class which inherits from the CActor we just created and place it anywhere in your level. Then, set the SM property to any cube in the default map, as seen in the image below:

casting_viewport

The arrows are showing which cube I choose and it’s respective name.

If you execute your code now, your output log should contain the following message:

casting_output

Avatar photo

This Post Has 3 Comments

  1. Hi!

    I’m new to unreal engine and I always wonder how you deal with memory management of pointers in unreal engine?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Back To Top