Unreal Snake Game 1.0.0
SG_ObjectPool.h
1// Snake Game, Copyright LifeEXE. All Rights Reserved.
2
3#pragma once
4
5#include "CoreMinimal.h"
6#include "UObject/NoExportTypes.h"
7#include "SG_ObjectPool.generated.h"
8
9UCLASS()
10class SNAKEGAME_API USG_ObjectPool : public UObject
11{
12 GENERATED_BODY()
13
14public:
15 template <typename ActorType>
16 void Reserve(UWorld* World, int32 Num, const TSubclassOf<AActor>& ActorClass)
17 {
18 if (!World) return;
19
20 for (int32 i = 0; i < Num; ++i)
21 {
22 ActorType* Actor = World->SpawnActor<ActorType>(ActorClass, FTransform::Identity);
23 Add(Actor);
24 }
25 }
26
27 template <typename ActorType>
28 ActorType* Pop(UWorld* World, const FTransform& Transform, const TSubclassOf<AActor>& ActorClass)
29 {
30 if (!World) return nullptr;
31
32 ActorType* Actor = Pool.IsEmpty() ? World->SpawnActor<ActorType>(ActorClass, Transform) : Cast<ActorType>(Pool.Pop());
33 check(Actor);
34 Actor->SetActorTransform(Transform);
35 Actor->SetActorHiddenInGame(false);
36 return Actor;
37 }
38
39 template <typename ActorType>
40 void Add(ActorType* Actor)
41 {
42 if (!Actor) return;
43 Actor->SetActorHiddenInGame(true);
44 Pool.Add(Actor);
45 }
46
47private:
48 UPROPERTY()
49 TArray<TObjectPtr<AActor>> Pool;
50};
Definition: SG_ObjectPool.h:11