Download

How do I "for loop" in C++ (I am coming from blueprints)

Hey Guys I managed to get some things in my first C++ code to work, feels like magic.
Right now the code creates a cube but I want i to make many many cubes think of it like minecraft.

It basically needs what blueprints have in the “for loop” function.

How do I achieve this?

My CubePlacer.cpp



#include "test.h"
#include "CubePlacer.h"


// Sets default values
ACubePlacer::ACubePlacer()
{
	Grabber = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("letmetakeaselfie"));
	static ConstructorHelpers::FObjectFinder<UStaticMesh> StaticMeshOb_torus(TEXT("StaticMesh'/Game/Geometry/Meshes/1M_Cube.1M_Cube'"));
	if (StaticMeshOb_torus.Object)
		Grabber->SetStaticMesh(StaticMeshOb_torus.Object);
}

// Called when the game starts or when spawned
void ACubePlacer::BeginPlay()
{
	Super::BeginPlay();
	
}


My CubePlacer.h


#pragma once

#include "GameFramework/Actor.h"
#include "CubePlacer.generated.h"

UCLASS()
class TEST_API ACubePlacer : public AActor
{
	GENERATED_BODY()
	
public:	
	// Sets default values for this actor's properties
	ACubePlacer();

	// Called when the game starts or when spawned
	virtual void BeginPlay() override;

	UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Base)
	class UStaticMeshComponent* Grabber;

	UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = CubeSize)
	class UStaticMesh* DesiredMesh;

	UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = CubeSize)
	int32 xCells;

	UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = CubeSize)
		int32 yCells;
	
	UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = CubeSize)
		int32 zCells;
};


Many many thanks!

The standard syntax for a for loop in C++ is as follows:


for ( init; condition; increment )
{
   statement(s);
}

An example of how someone might use this is:


for ( i = 0; i < 10; i++ )
{
  Mesh = MeshArray*
}

My example in blueprints would be a for loop from indexes 0 to 9, that sets a mesh variable to be the ‘Find Item’ result in the loop’s index.

Alternatively, you could change the increment parameter to be “i += 2” to increment by 2 indices each time.

Also you can use new c++ range based for to iterate throug FMap entries

But remember to use const references, not value type to ommit unintentional copying of elements. You can also use const auto & in place of const FVector & - so the compiler will calculate and substitute type automatically.
Also there are some more options and explanations here A new, community-hosted Unreal Engine Wiki - Announcements and Releases - Unreal Engine Forums