UE5 对象池 一个umg和actor的对象池

该文章展示了在UnrealEngine中实现的一个名为UObjectPoolSubsystem的系统,用于管理游戏中的对象池,如Actor和UserWidget。它包含FActorPool结构,用于存储和检索Actor实例,支持对象的创建、释放和重用,优化游戏性能。

.h文件

// Copyright Access! GameStudio. All Rights Reserved.

#pragma once

#include "CoreMinimal.h"
#include "Blueprint/UserWidgetPool.h"
#include "Subsystems/WorldSubsystem.h"
#include "ObjectPoolSubsystem.generated.h"

/**
 * 
 */

USTRUCT(BlueprintType)
struct FActorPool
{
   
   
	GENERATED_BODY()

public:

	FActorPool(){
   
   };
	void SetWorld(UWorld* World)
	{
   
   
		if(World)
		{
   
   
			OwningWorld = World;
		}
	}
	bool IsInitialized() const {
   
    return OwningWorld.IsValid(); }

	AActor* GetActor(TSubclassOf<AActor> ActorClass);

	//创建actor
	template <typename ActorT = AActor>
	AActor* GetOrCreateActor(TSubclassOf<ActorT> ActorClass)
	{
   
   
		if (!ActorClass || !ensure(IsInitialized()))
		{
   
   
			return nullptr;
		}

		AActor* Actor = nullptr;
		for (AActor* InactiveActor : InactiveActors)
		{
   
   
			if (InactiveActor->StaticClass() == ActorClass)
			{
   
   
				Actor = InactiveActor;
				InactiveActors.RemoveSingleSwap(InactiveActor);
				break;
			}
		}
		if(Actor)
		{
   
   
			SetActorEnable(Actor,true);
		}
		if (!Actor)
		{
   
   
			Actor = OwningWorld.Get()->SpawnActor(ActorClass);
			if (!Actor)
			{
   
   
				return nullptr;
			
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值