Download

How do you use global UStructs in C++ ?

I have my FTestStruct compiled successfully. I created the .h file from within visual studio and included it in the header MyProjectName.h. I am at a loss as to how to actually create a variable in another class with it. How Would I call it? All i want to do is put 3 values into it exactly like you would with an FVector.



#pragma once
#include "CoreMinimal.h"
#include "LocalRoomVectorGrid.generated.h"


USTRUCT()
struct FTestStruct
{
    GENERATED_BODY()

public:


    UPROPERTY(EditAnywhere)
        int32 Value1 = 0;

    UPROPERTY(EditAnywhere)
        int32 Value2 = 0;

    UPROPERTY(EditAnywhere)
        int32 Value3 = 0;

    FTestStruct()
    {

    }
};



When i try the following in MyCharacter.CPP I get the error : error C2440: ‘’: cannot convert from ‘initializer list’ to ‘FTestStruct’




**FTestStruct Test = FTestStruct(1, 2, 3);**



You have no constructor that takes the parameters as described.

I have found a forum post on structure initialization which can be found at Structs, how to initialize one as a variable? - C++ Gameplay Programming - Unreal Engine Forums

If you don’t wish to specify a constructor with all your structure parameters, you can also do something like the following:



FTestStruct Test = FTestStruct();

Test.Value1 = 1;
Test.Value2 = 1;
Test.Value3 = 1;

// And so forth


Or specify a constructor to take your variables



#pragma once
#include "CoreMinimal.h"

#include "LocalRoomVectorGrid.generated.h

USTRUCT()
struct FTestStruct
{
    GENERATED_BODY()

public:

    UPROPERTY(EditAnywhere)
        int32 Value1 = 0;

    UPROPERTY(EditAnywhere)
        int32 Value2 = 0;

    UPROPERTY(EditAnywhere)
        int32 Value3 = 0;

    FTestStruct()
    {}

    FTestStruct(int32 Value1Param, int32 Value2Param, int32 Value3Param) : Value1(Value1Param), Value2(Value2Param), Value3(Value3Param)
    {}
};


And call like so:



FTestStruct Test(1,2,3);


THANK YOU VERY VERY MUCH.
That is exactly what i was doing wrong.
And thank you for explaining more than one method!

You can also use


GENERATED_USTRUCT_BODY()

instead of GENERATED_BODY()

Is there any reason to use one over the other?
I read on the wiki: “In case you are looking for GENERATED_USTRUCT_BODY, in 4.11+, GENERATED_BODY() should be used instead.”

Generated_Body() makes a call to Generated_Struct() if necessary.
It doesn’t matter, can use any you like.