Hello, I’m a newbie in C++ and I haven’t been around Unreal for a long time. Excuse me for the stupid question.
I’m developing a game with an analysis system. So we created a class called “Analysis System” with analysis elements as variables. I want to use it by declaring it as an object in the Character.
This object is retained and the value is not initialized each time it is called. You must continue to calculate the same value.
I thought I could declare this in the header file, but it wasn’t. It doesn’t work as I intended.
[MyCharacter:: AnSysuses Undefined class “Analysis System”] This is my error.
Please see the minimum reproducible code below and help. Thank you.
MyCharacter.h
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Character.h"
#include "InputActionValue.h"
#include "projectCharacter.generated.h"
DECLARE_MULTICAST_DELEGATE(FOnAttackEndDelegate);
UCLASS(config = Game)
class AprojectCharacter : public ACharacter
{
GENERATED_BODY()
public:
AMyCharacter();
class AnalysisSystem AnSys;
}
AnalysisSystem.h
#pragma once
#include "CoreMinimal.h"
class PROJECT_API AnalysisSystem
{
public:
AnalysisSystem();
}
I solved this by declaring it as a global variable in the cpp file. It works the way I want it to, but I don’t know if this is the best way. Help me if you know the best way!
class AnalysisSystem* AnSys = new AnalysisSystem();
The first is that your original code (the one not using a pointer) would work just fine if you included the AnalysisSystem header instead of doing class AnalysisSystem. This is because what you’re doing in an inline forward declaration and you can’t use forward declarations to declare instances. You can declare pointers, which is why that is allowed to compile. If you go with this option, you should declare AnalysisSystem as a struct and use the USTRUCT macro when you declare it.
The second option is to leave it as a pointer, but to change your class to derive from UObject and use the UCLASS macro. In this case, you’ll also want to use the UPROPERTY macro on the pointer in your character class. In the struct case this is optional, but still recommended.
This is because unlike vanilla C++, Unreal is meant to handle object allocation in the majority of cases. You’ll find that even though it compiles, you’ll probably have a lot of other problems trying to get your character to work properly. Generally doing allocations with new in Unreal is a red flag and should be considered very carefully and with a lot of understanding of how the Engine, reflection and the garbage collector work.