Manually Create Foliage C++

Hi,

I am currently working on a project and I need to be able to spawn in bushes which are foliage types in a similar way to the way I spawn in actors. Basically I would like someone to either point me to the file where the foliage painting tool actually spawns foliage type objects into the world or better still provide me with a better idea of how I can achieve what I stated above.

Thanks in advance

Hi. this is my code that i use to do that

	TActorIterator<AInstancedFoliageActor> foliageIterator(GetWorld());
	AInstancedFoliageActor* foliageActor = *foliageIterator;

	//if you already have foliage in your level, you just need to get the right component, one is created for each type
	TArray<UInstancedStaticMeshComponent*> components;
	foliageActor->GetComponents<UInstancedStaticMeshComponent>(components);
	UInstancedStaticMeshComponent* meshComponent = components[0];

	//Now you just need to add instances to component, this example crate 400 instances
	FTransform transform = FTransform();
	for (int32 x = 1; x < 20; x++)
	{
		for (int32 y = 1; y < 20; y++)
		{
			transform.SetLocation(FVector(1000.f * x, 1000.f * y, 0.f));
			meshComponent->AddInstance(transform);
		}
	}

Also, If you need to create the instanced static mesh component too, this is my code that i use

UInstancedStaticMeshComponent* meshComponent = NewObject<UInstancedStaticMeshComponent>(foliageActor, UInstancedStaticMeshComponent::StaticClass(), NAME_None, RF_Transactional);
	meshComponent->AttachTo(foliageActor->GetRootComponent());
	meshComponent->SetStaticMesh(MyStaticMesh);
	meshComponent->RegisterComponent();

Note: you need to inlcude “Runtime/Foliage/Public/InstancedFoliageActor.h”

Regards

1 Like

Note2: one also needs to add Foliage to the PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore", "Foliage"});

I’m having a weird issue, using @Horacio27 code I try to delete all the spawned foliage

	for (int32 i = 0; i < components.Num(); i++)
	{
		int32 k = components[i]->GetInstanceCount();

		for (int32 j = 0; j < k; j++)
		{	
			if(components[i]->RemoveInstance(j))
				UE_LOG(LogTemp, Warning, TEXT("deleted %d of %d"), j+1, k);
		}
	}

It clears half of the map, the other half remains intact.
The log confirms this, last line is.

LogTemp: Warning: deleted 1632 of 3264

Any idea why this is happening?

EDIT: figured it out, the array is shrinked every time an element is removed.