Hi!
I’m currently working on my first project and trying to solve something like a pool for ingame items that might drop after defeating an enemy. For the moment I’d like to provide some kind of a static “database” for the pool (static setup of 5-10 items), so I’m using a TMap
that should be filled on game start and I only need one instance.
I implemented two approaches (as my first one did not work) and some variations… let me explain those and forgive me to paste a lot of code (as I think it might be helpful to expain my question)
- Pure C++
class ItemPool
{
public:
ItemPool();
RawItem* GetWeaponItem(const FName ItemName);
private:
TMap<FName, RawItem*> Weapons;
};
- As UObject
UCLASS(NotBlueprintable)
class PROTOTYPE_20241003_API UItemPool : public UObject
{
GENERATED_BODY()
public:
URawItem* GetWeaponItem(const FName ItemName);
private:
UPROPERTY(VisibleDefaultsOnly)
TMap<FName, URawItem*> Weapons = TMap<FName, URawItem*>();
And here is the usage:
UCLASS(Blueprintable)
class PROTOTYPE_20241003_API UItemSpawner : public UActorComponent
{
GENERATED_BODY()
public:
UItemSpawner()
{
UItemPool = CreateDefaultSubobject<UItemPoolU>("ItemPool");
ItemPool = new NewItemPool();
};
UFUNCTION(BlueprintCallable)
void SpawnWeaponActor(FName ItemName);
private:
UPROPERTY(VisibleDefaultsOnly)
TObjectPtr<UItemPool> UItemPool;
ItemPool* ItemPool;
};
So, whenever I use the UItemPool (UObject) I don’t retrieve items from my implementation and get access violations etc. (or no item is returned as the map is empty). I guess the instance of my UObject is removed by GC…
Not sure why I can’t keep an instance like that. So one “workaround” for the current phase could be to use a either a fresh instance on every call (UItemPool* ItemPool = NewObject<UItemPool>();
) or to use a static approach.
On the other hand the pure C++ implementation is working out of the box as expected. No need to make it a UPROP etc.
So, you guessed it… my questions
- Is it okay to use pure C++?
- Do I need to keep track of pointers (in pure C++) and free the memory in deconstructors?
- when should I switch to Unreal framework? what are are advantages?
- why is my UObject implementation not working? (when using the basic implementation, not the fresh classes on call or static)
Thanks for reading. Answers are much appreciated