LEAP Documentation 40220
Documentation for the LEAP project
ObjectPool.h
Go to the documentation of this file.
1// Copyright Blue Isle Studios Inc 2021. All Rights Reserved.
2
3#pragma once
4
5#include "CoreMinimal.h"
6#include "GameFramework/Actor.h"
7#include "ObjectPool.generated.h"
8
9#define DEBUG_OBJECT_POOL 0
10
11UCLASS()
12class PROJECTX_API AObjectPool : public AActor
13{
14 GENERATED_BODY()
15
16public:
18
19 static TMap<TWeakObjectPtr<UWorld>, AObjectPool*> Singleton;
20 TMap<TSubclassOf<AActor>, TArray<AActor*>> ObjectPool;
21
22 static AObjectPool* Get(UObject* const WorldContextObject);
23 virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override;
24
25 template< class T >
27 UClass* Class,
28 FTransform const& Transform,
29 AActor* Owner = nullptr,
30 AActor* Instigator = nullptr
31 )
32 {
33 UWorld* const World = GetWorld();
34 if (!World || World->bIsTearingDown)
35 {
36 return nullptr;
37 }
38
39 if (!ObjectPool.Contains(Class))
40 {
41 ObjectPool.Add(Class);
42 }
43
44 TArray<AActor*>& AvailablePool = ObjectPool[Class];
45 for (int i = AvailablePool.Num()-1; i >= 0; i--)
46 {
47 AActor* const SpawnedActor = AvailablePool[i];
48 AvailablePool.RemoveAt(i);
49
50 if (!SpawnedActor || SpawnedActor->IsPendingKillPending())
51 {
52 continue;
53 }
54
55 SpawnedActor->SetOwner(Owner);
56 SpawnedActor->SetInstigator(Instigator);
57 SpawnedActor->SetActorTransform(Transform);
58
59 #if DEBUG_OBJECT_POOL
60 UE_LOG(LogTemp, Log, TEXT("[Object Pool] Reuse Actor '%s' from pool. Available of type: %d"), *SpawnedActor->GetName(), AvailablePool.Num());
61 #endif
62
63 return Cast<T>(SpawnedActor);
64 }
65 #if DEBUG_OBJECT_POOL
66 UE_LOG(LogTemp, Log, TEXT("[Object Pool] Spawned Actor '%s'. No pool actors available. Will cache to pool."), *Class->GetName());
67 #endif
68 return World->SpawnActorDeferred<T>(Class, Transform, Owner, Instigator, ESpawnActorCollisionHandlingMethod::AlwaysSpawn);
69 }
70
71 void FinishSpawning(AActor* const Actor, FTransform const& Transform);
72 void ReleaseActorToPool(AActor* const Actor);
73};
Definition: ObjectPool.h:13
TMap< TSubclassOf< AActor >, TArray< AActor * > > ObjectPool
Definition: ObjectPool.h:20
T * SpawnActorDeferred(UClass *Class, FTransform const &Transform, AActor *Owner=nullptr, AActor *Instigator=nullptr)
Definition: ObjectPool.h:26
static TMap< TWeakObjectPtr< UWorld >, AObjectPool * > Singleton
Definition: ObjectPool.h:19