How to organize functionality to separate classes correctly?

Hello,

I’m writing some functionality in a UActorComponent which became too long and cluttered, so I’d want to extract some of it to another class that will be responsible for just that, hopefully making the code in the first class a lot more readable.

This other class will handle shooting LineTraces and Sweeps for me based on whatever data I pass to it in a struct. This means that it’ll need a pointer to UWorld.

I wonder how to do this correctly.

My first instinct was to create a plain c++ class that receives the UWorld* as its constructor parameter

class MyHelperClass 
{
private:
    UWorld* World;

public:
    MyHelperClass(UWorld* World): World(World) {}
}

and instantiate this class in my UActorComponent as

UCLASS()
class MY_API UMyActorComponent : public UActorComponent
{
    GENERATED_BODY()

private:
    TUniquePtr<MyHelperClass> Helper;
}

and in begin play

void UMyActorComponent::BeginPlay()
{
    Helper = MakeUnique<MyHelperClass>(GetWorld());
}

However, I have concerns that a non UObject has a raw pointer to UWorld.

What should be the correct way to handle this? Should I just derive MyHelperClass from UObject instead and use NewObject?

Note that the purpose of MyHelperClass is only to make the code easier to maintain, so it won’t be instantiated in the scene itself, or anything like that. Technically I could just put everything in one class but it looks bad already so I wanted to separate some functionality into responsible classes.

1 Like