目录
角色生成器,生成克隆角色
- // 抽象原型类 —— 怪物
- UCLASS(Abstract)
- class DESIGNPATTERNS_API UMonsterPrototype : public UObject
- {
- GENERATED_BODY()
- public:
- // 克隆函数
- virtual UMonsterPrototype* Clone() {
- UE_LOG(LogTemp, Error, TEXT("Please implement this!"));
- return nullptr;
- }
-
- // 展示信息
- virtual void ShowInfo() {
- UE_LOG(LogTemp, Warning, TEXT(__FUNCTION__" %s [Health]%d, [Speed]%d"), *this->GetName() ,m_pHealth, m_pSpeed);
- }
-
- protected:
- int32 m_pHealth = 100;
- int32 m_pSpeed = 30;
- };
- // 具体产原型类 —— Ghost
- UCLASS(Blueprintable, BlueprintType)
- class DESIGNPATTERNS_API UGhost : public UMonsterPrototype
- {
- GENERATED_BODY()
- public:
-
- // 重载克隆函数
- virtual UMonsterPrototype* Clone() override {
- UGhost* CloneIns = NewObject
(); - CloneIns->m_pHealth = m_pHealth;
- CloneIns->m_pSpeed = m_pSpeed;
- return CloneIns;
- }
- };
-
- // 具体产原型类 —— Devil
- UCLASS(Blueprintable, BlueprintType)
- class DESIGNPATTERNS_API UDevil : public UMonsterPrototype
- {
- GENERATED_BODY()
- public:
- // 初始化数值
- UDevil() {
- m_pHealth = 120;
- m_pSpeed = 20;
- }
-
- // 重载克隆函数
- virtual UMonsterPrototype* Clone() override {
- UDevil* CloneIns = NewObject
(); - CloneIns->m_pHealth = m_pHealth;
- CloneIns->m_pSpeed = m_pSpeed;
- CloneIns->m_pAttack = m_pAttack;
- return CloneIns;
- }
-
- // 展示信息
- virtual void ShowInfo() override {
- UE_LOG(LogTemp, Warning, TEXT(__FUNCTION__" %s [Health]%d, [Speed]%d, [Attack] %d"), *this->GetName(), m_pHealth, m_pSpeed, m_pAttack);
- }
- protected:
- int32 m_pAttack = 100;
- };
- // 工厂类 —— 怪物生成器
- UCLASS(Blueprintable, BlueprintType)
- class DESIGNPATTERNS_API UMonsterSpawner : public UObject
- {
- GENERATED_BODY()
- public:
-
- // 生成新怪物,使用模板,避免针对每种怪物都要写一遍
- template <class T>
- T* SpawnMonster() {
- return NewObject
(); - }
-
- // 克隆怪物
- UMonsterPrototype* SpawnMonster(UMonsterPrototype* pMonsterClass) {
- return pMonsterClass->Clone();
- }
- };
测试
- // 调用测试用的Actor
- UCLASS()
- class DESIGNPATTERNS_API AMonsterSpawnerActor : public AActor
- {
- GENERATED_BODY()
- public:
-
- void BeginPlay() override {
-
- // 创建工厂
- UMonsterSpawner* MonsterSpawner = NewObject
(); -
- // 第一次创建 Ghost
- UGhost* Ghost = MonsterSpawner->SpawnMonster
(); - // 克隆 Ghost
- UGhost* Ghost_Copy1 = Cast
(MonsterSpawner->SpawnMonster(Ghost)); - Ghost->ShowInfo();
- Ghost_Copy1->ShowInfo();
-
- // 第一次创建 Devil
- UDevil* Devil =MonsterSpawner->SpawnMonster
(); - // 克隆 Devil
- UDevil* Devil_Copy1 = Cast
(MonsterSpawner->SpawnMonster(Devil)); - Devil->ShowInfo();
- Devil_Copy1->ShowInfo();
- }
- };
- LogTemp: Warning: UMonsterPrototype::ShowInfo Ghost_0 [Health]100, [Speed]30
- LogTemp: Warning: UMonsterPrototype::ShowInfo Ghost_1 [Health]100, [Speed]30
- LogTemp: Warning: UDevil::ShowInfo Devil_0 [Health]120, [Speed]20, [Attack] 100
- LogTemp: Warning: UDevil::ShowInfo Devil_1 [Health]120, [Speed]20, [Attack] 100