How to set range for the FTransform Array?

Goys what I am doing wrong in my C++ conversion of this bp script?

void AMyGameMode::RandomLocation(TArray<FTransform> Available, FTransform& Location)
{
	FTransform GetByCopy{};
	GetByCopy = Available[FMath::RandRange(1, Available.Num() - 1)]; 
	Location = GetByCopy;
}

I noticed you like to pass something by reference to get some value, it’s ok but you can also make the function return something similar to your BP example

If you want to return by copy. (passing by const ref is recommened)
FTransform GetRandomLocation(const TArray<FTransform>& Available);

FTransform AMyGameMode::GetRandomLocation(const TArray<FTransform>& Available)
{
	return Available[FMath::RandRange(0, Available.Num() - 1)];
}

If you want to return by reference:
FTransform& GetRandomLocation(TArray<FTransform>& Available);

FTransform& AMyGameMode::GetRandomLocation(TArray<FTransform>& Available)
{
	return Available[FMath::RandRange(0, Available.Num() - 1)];
}

Usage:
FTransform& VarByRef = GetRandomLocation(Arr);

Make sure you check the array Available has > 0 elements.

2 Likes

Thank you for correcting me, I was actually not checking the array if > 0 , you just solved my Issue, thank you so much :slight_smile:

image_2022-08-14_225910174

and how to pass GetAllTransform output in RandomLocation()?

I am trying this but no seccess

//Creating ItemGroup Reference which takes transforms of items
TSubclassOf<AActor> AItemGroup = AActor::StaticClass();
AActor* ItemGroupRef = GetWorld()->SpawnActor<AActor>(AItemGroup, SpawnTransform, SpawnInfo);

//Passing the transfrom Stored in ItemGroupRef
RandomLocation(ItemGroupRef->GetAllTransforms());

I solved it.

//I was trying which is wrong but I don't know why this is wrong or how to pass a function under funciton.
TArray<FTransform> GetAllTransformsRef{};
RandomLocation(ItemGroupRef->GetAllTransforms(GetAllTransformsRef));

and

// Solution
TArray<FTransform> GetAllTransformsRef{};
ItemGroupRef->GetAllTransforms(GetAllTransformsRef);
RandomLocation(GetAllTransformsRef);