Download

Spawning meshes from an array?

Hi guys,

I wanting to spawn a random mesh from an array but I’m not quite understanding what to do.

I’ve got the below code:



	Platform = ObjectInitializer.CreateAbstractDefaultSubobject<UStaticMeshComponent>(this, TEXT("Floor_StaticMesh"));

	static ConstructorHelpers::FObjectFinder <UStaticMesh>StaticMesh(TEXT("StaticMesh'/Game/Meshes/Floor_StaticMesh.Floor_StaticMesh'"));

	Platform->SetStaticMesh(StaticMesh.Object);

	RootComponent = Platform;



Which lets me spawn an actor with the below code in the GameMode class:


World->SpawnActor<ALevelGen>(ALevelGen::StaticClass(), FVector(0, 0, -400), FRotator(0,0,0));

I’m just not sure where to go from there? How would I actually spawn more than one from an array?

Regards,

acidrainlte

Sorry…does no one have any advice on this?

well you would have to create an array…


UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = MeshSomething)
TArray<UStaticMesh*> Meshes;

then add some actual meshes to it (best done via a blueprint subclass).

From here, it depends on your actual logic. Do you want a random mesh out of the array? all of them? serveral random meshes etc.

Let’s say you want to spawn all of them, iterate over the array with either a for-loop or an iterator and Spawn StaticMeshActors and set the Mesh for each one.

Hi, thanks for the reply! Yes, I’ve got the array set up, I just didn’t bother including that single line of code.

I just want to spawn a random mesh from it. How would I change the below code to do that?

“World->SpawnActor<ALevelGen>(ALevelGen::StaticClass(), FVector(0, 0, -400), FRotator(0,0,0));”




Well, meshes itself aren’t spawnable, since they they aren’t Actors. So you have to Spawn an Actor that has a StaticMeshComponent and then set it dynamically based on what ever you randomly picked out of the array.

.h


UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = MeshSomething)
TArray<UStaticMesh*> Meshes;

.cpp



	if (Meshes.Num() == 0)
		return;

	int32 randIndex = FMath::RandRange(0, Meshes.Num() - 1);



	if (Meshes[randIndex] != NULL)
	{
		AStaticMeshActor* SpawnedActor = GetWorld()->SpawnActor<AStaticMeshActor>(AStaticMeshActor::StaticClass(), SpawnLocation, SpawnRotation);
		if (SpawnedActor)
		{
	                //mobility only needed for AStaticMeshActor
			SpawnedActor->SetMobility(EComponentMobility::Movable);
			SpawnedActor->GetStaticMeshComponent()->SetStaticMesh(Meshes[randIndex]);
		}

	}

then just make a Blueprint subclass of this and fill the Meshes array with actual meshes you want to spawn. Done.

Change the AStaticMeshActor to the whatever class you want to spawn. But your class needs a StaticMeshComponent for this to work.

Thanks! Sorry, this seems so simple…I obviously just don’t have my programming brain on these days.

Glad I could help :stuck_out_tongue: