UE4 在Actor Component中给Actor动态创建Component

版本UE4.20

创建C++ Class,继承自Actor Component,以动态创建SceneCaptureComponent2D为例。

.h

// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

#include "CoreMinimal.h"
#include "Components/ActorComponent.h"
#include "MyActorComponent.generated.h"

class USceneCaptureComponent2D;
class UTextureRenderTarget2D;
UCLASS( ClassGroup=(Custom), meta=(BlueprintSpawnableComponent) )
class MYPROJECT_API UMyActorComponent : public UActorComponent
{
	GENERATED_BODY()

public:	
	// Sets default values for this component's properties
	UMyActorComponent();

	UFUNCTION(BlueprintCallable, Category = "Actor Com")
		bool  Init2DCaptureComponent( USceneComponent* Parent, UTextureRenderTarget2D*  RenderTargets);
protected:
	// Called when the game starts
	virtual void BeginPlay() override;

public:	
	// Called every frame
	virtual void TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) override;

		
	
};

.cpp

// Fill out your copyright notice in the Description page of Project Settings.

#include "MyActorComponent.h"
#include "Components/SceneCaptureComponent2D.h"
#include "Engine/TextureRenderTarget2D.h"
#include "UObject/UObjectGlobals.h"
#include "GameFramework/Actor.h"

// Sets default values for this component's properties
UMyActorComponent::UMyActorComponent()
{
	// Set this component to be initialized when the game starts, and to be ticked every frame.  You can turn these features
	// off to improve performance if you don't need them.
	PrimaryComponentTick.bCanEverTick = true;

	// ...
}


// Called when the game starts
void UMyActorComponent::BeginPlay()
{
	Super::BeginPlay();

	// ...
	
}


// Called every frame
void UMyActorComponent::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
{
	Super::TickComponent(DeltaTime, TickType, ThisTickFunction);

	// ...
}

bool UMyActorComponent:: Init2DCaptureComponent(USceneComponent* Parent, UTextureRenderTarget2D*  RenderTargets)
{
	if (Parent == nullptr || RenderTargets == nullptr)
	{
		return false;
	}
		USceneCaptureComponent2D* New2DCamera = NewObject(GetOwner());
		New2DCamera->AttachToComponent(Parent, FAttachmentTransformRules::KeepRelativeTransform);
		New2DCamera->RegisterComponent();  //注意必不可少,否则创建的组件不起作用
		New2DCamera->TextureTarget = RenderTargets;
		New2DCamera->CaptureSource = ESceneCaptureSource::SCS_FinalColorLDR;
		New2DCamera->PrimitiveRenderMode = ESceneCapturePrimitiveRenderMode::PRM_RenderScenePrimitives;
		New2DCamera->SetRelativeRotation(FRotator(0.0, 90.0, 0.0));

	return New2DCamera->IsRegistered();
}

创建一个Actor蓝图

UE4 在Actor Component中给Actor动态创建Component_第1张图片

运行

UE4 在Actor Component中给Actor动态创建Component_第2张图片

结果:

UE4 在Actor Component中给Actor动态创建Component_第3张图片

 

 

 

 

 

 

你可能感兴趣的:(UE4)