Here is the problem code: .h // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "Components/InstancedStaticMeshComponent.h"
#include "MyActorForISMTest.generated.h"
UCLASS()
class ISMTEST_API AMyActorForISMTest : public AActor
{
GENERATED_BODY()
UPROPERTY(EditAnywhere, Category = "test")
AActor * myObj;
public:
TMap<size_t, UInstancedStaticMeshComponent *> mapForISMC;
TArray <size_t> arrayHaveColor;
int totalNum;
public:
// Sets default values for this actor's properties
AMyActorForISMTest();
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
public:
// Called every frame
virtual void Tick(float DeltaTime) override;
};
.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "MyActorForISMTest.h"
// Sets default values
AMyActorForISMTest::AMyActorForISMTest()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
totalNum = 3000;
}
// Called when the game starts or when spawned
void AMyActorForISMTest::BeginPlay()
{
Super::BeginPlay();
UWorld* World = myObj->GetWorld();
UClass * muClass = myObj->GetClass();
for (size_t i = 0; i < totalNum; i++)
{
AActor* actorPtr = World->SpawnActor<AActor>(muClass, FVector(0, 0, 0), FVector(0, 0, 0).Rotation());
actorPtr->AttachToActor(this, FAttachmentTransformRules(EAttachmentRule::KeepWorld, false));
actorPtr->SetOwner(this);
UStaticMeshComponent* mCube = actorPtr->FindComponentByClass<UStaticMeshComponent>();
mCube->SetMobility(EComponentMobility::Static);
UMaterialInstanceDynamic* mMaterial = UMaterialInstanceDynamic::Create(mCube->GetMaterial(0), NULL);
mCube->SetMaterial(0, mMaterial);
mapForISMC.Add(i, actorPtr->FindComponentByClass<UInstancedStaticMeshComponent>());
}
}
// Called every frame
void AMyActorForISMTest::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
arrayHaveColor.Empty();
for (size_t i = 0; i < totalNum; i++)
{
mapForISMC[i]->ClearInstances();
}
for (size_t i = 0; i < totalNum; i++)
{
arrayHaveColor.Add(i);
}
for (size_t i = 0; i < totalNum; i++)
{
size_t tempIndex = arrayHaveColor[i];
FInstancedStaticMeshInstanceData insData;
mapForISMC[i]->PerInstanceSMData.Add(insData);
}
}
That will cause memory leak.Because too many InstancedStaticMeshComponent need update in Tick function.After I put all insData in one InstancedStaticMeshComponent,problem solved.But the reason detail still unclear for me.
answered
Nov 27 '18 at 02:11 AM
孤城太守
1
●
1
●
1
seems like peroblem with materials. I test below. clear then add ISM to tarray PerInstanceSMData in Tick(),works fine without memory leak. .h
.cpp
set AActor * myObj