Loading assets into components using FObjectFinder

In the last recipe, we created a Static Mesh Component, but we didn't try to load a mesh for the Component to display. While it's possible to do this in the Editor, sometimes it is helpful to specify a default in C++.

Getting ready

Follow the previous recipe so you have a custom Actor subclass with a Static Mesh Component ready.

In your Content Browser, click on the View Options button, and select Show Engine Content:

Getting ready

Browse to Engine Content, then BasicShapes to see the Cube we will be using in this recipe.

Getting ready

How to do it...

  1. Add the following code to the constructor of your class:
    auto MeshAsset = ConstructorHelpers::FObjectFinder<UStaticMesh>(TEXT("StaticMesh'/Engine/BasicShapes/Cube.Cube'"));
    if (MeshAsset.Object != nullptr)
    {
      Mesh->SetStaticMesh(MeshAsset.Object);
    }
  2. Compile, and verify in the Editor that an instance of your class now has a mesh as its visual representation.

How it works...

  • We create an instance of the FObjectFinder class, passing in the type of asset that we are trying to load as a template parameter.
  • FObjectFinder is a class template that helps us to load assets. When we construct it, we pass in a string that contains a path to the asset that we are trying to load.
  • The string is of the format "{ObjectType}'/Path/To/Asset.Asset'". Note the use of single quotes in the string.
  • In order to get the string for an asset that already exists in the editor, you can right-click on the asset in the Content Browser and select Copy Reference. This gives you the string so you can paste it into your code.
    How it works...
  • We use the auto keyword, from C++11, to avoid typing out our whole object type in its declaration; the compiler deduces it for us. Without auto, we would have to use the following code instead:
    ConstructorHelpers::FObjectFinder<UStaticMesh> MeshAsset = ConstructorHelpers::FObjectFinder<UStaticMesh>(TEXT("StaticMesh'/Engine/BasicShapes/Cube.Cube'"));
  • The FObjectFinder class has a property called Object that will either have a pointer to the desired asset, or will be NULL if the asset could not be found.
  • This means that we can check it against nullptr, and if it isn't null, assign it to Mesh using SetStaticMesh.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.231.26