How can I create a separate header for my Structs?

Hi there. I’m just starting to use Structs throughout my project and I was wondering what the process is to create a separate header containing a selection of non-specific Structs that I can use inside different classes? Like a ‘MyGlobalStructs.h’

Also, is there anything else I need to know if I create Structs outside of a default Unreal class? I understand Structs aren’t garbage collected so do I need to do anything else if I place them inside a separate header file?

(I don’t really know what the hell im doing to be honest haha)

I have only created classes through the built in menus from within the editor so I’m trying to not to mess everything up haha.

Thanks for any help!

Pretty much like so:

#pragma once

#include "CoreMinimal.h"
#include "MyGlobalStructs.generated.h"

USTRUCT()
struct FMyFirstGlobalStruct
{
    GENERATED_BODY()

    UPROPERTY()
    AActor* SomeActorReference;

    UPROPERTY(EditDefaultsOnly)
    float DefaultActorHealth = 100.f;
};

Here’s what’s going on in the snippet above:

  1. The “…generated.h” include is only necessary if you have structs or enums in that header file that start with the USTRUCT or UENUM macros. If not, it’s not only not necessary, the compiler will complain about it being there.
  2. The GENERATED_BODY part only works inside structs that start with the USTRUCT macro. If you have a plain old struct you don’t need any of that. See the FInputModeDataBase struct in the engine source for example.
  3. Structs are not garbage collected, but they usually don’t have to be. Properties inside those structs might have to, though. Like the actor reference above. In order to tell the GC that there’s an actor pointer in there that needs to be garbage collected, you put the UPROPERTY macro in front of it, just like you would do in UObject-derived classes.
  4. You can choose to put UPROPERTY macros in fron of other properties in your structs if you want them to be editable in the editor. See the float property above.
  5. If you want to assign the struct to anything from within the editor or if you want to set properties on the struct in the editor, you need to put BlueprintType between the USTRUCT parentheses, like so: USTRUCT(BlueprintType).

That’s the basics I’d say.

3 Likes

Thank you for this detailed answer! Extremely helpful to get me started using Structs with a little more confidence.