Download

How can I loop on only fraction of Array?

I currently have this:


void AShooterCharacter::FindNewMag(TArray<class UItem*> Items)
{
if (Gun == nullptr)
{
return;
}



for (auto Item : Items)
{
if (Item->IsA(UMagItem::StaticClass()))
{

if (Item == nullptr)
{
return;
}
Item->Use(this);

FoundMagIndex = FoundMagIndexBefore;

UE_LOG(LogTemp, Error, TEXT("Laduje"));
return;

}
else
{
UE_LOG(LogTemp, Warning, TEXT("Index now: %i"),FoundMagIndexBefore);

}
}
}

I want to get index of selected mag, and when this function is called again, loop should start from next index.
My problem is, I really don’t know how to do this.

You’d have to use a raw loop


for (int x = 0; x < Items.Num(); ++x)

instead of a ranged for.
If you have an index stored on AShooterCharacter, you can start the loop from there instead of 0.

You could also take that index as a parameter and return the found index for the caller to store instead. Storing the variable in AShooterCharacter could be a problem if different arrays of items are passed in.

Thanks. Now, how can I get magazine index when I have pointer to magazine?

Well, in your case since the items in the array are pointers you should be able to use either of the Find functions provided by TArray. One returns the index (and returns INDEX_NONE if it’s not found) while the other returns a boolean and has an int& param you pass in to be filled out with the index (which can be treated as valid if the function returns true).