Creating a simple object in UE4 C++ code does not work

Hey guys, I cant seem to make create a simple object in ue4 c++.
I have these two different classes:
RandomGenActor.h - > UClass of AActor
RandomGenActor.cpp

and another
CarClass.h → is just a blank class
CarClass.cpp

And what I want to do is to create an object of CarClass inside RandomGenActor, here’s what I want to do:
to declare

CarClass * CarC = new CarClass;

inside RoomGenActor

but I’m getting compilation errors, any idea what is the proper way to do this? Thanks!

While that’s the typical C++ way of creating a new object, you want to use UWorld::SpawnActor so that it registers your object in the engine properly.

Here’s a reference: Spawning Actors in Unreal Engine | Unreal Engine 5.1 Documentation

Does it really have to be an actor? Is there no other way?
I’ve come across this post but the method that I tried here doesnt work, I havent tried constructing the object like the second method mentioned here yet.

Make your class inheriting UObject and use the NewObject() method to create your derived UObject.

oh okay, I’ll try that.
Anyways, is it also okay if I just code all objects in different classes and just have them communicate in a blueprint if thats possible?

Yeah that’s possible, you can create blueprint_implementable functions in your class and expose all the member variables to blueprints, but it might be more work than it’s worth, depending on what you’re trying to accomplish.

I do this. I just declare it (my custom class) as an instance variable as part of my AActor derived class and I don’t have the compile issues. However it is problematic if the actor gets re-used or serialised from some reason.

Can you show me how you did it? Thanks!

I’m trying to implement a certain algorithm. What method would you recommend? Thank you