I have this piece of code:
for (FTankSpawn tankSpawn : tankSpawns)
{
if (tankSpawn.getLocation() == spawnLocation)
{
tankSpawn.setDestroyed(true);
}
}
Where tankSpawns is:
TArray<FTankSpawn> tankSpawns;
FTankSpawn is just a struct :
USTRUCT(BlueprintType)
struct FTankSpawn
{
GENERATED_BODY()
private:
UPROPERTY()
bool destroyed;
public:
void setDestroyed(bool destroyed) { this->destroyed = destroyed; }
FTankSpawn()
{
destroyed = false;
}
};
When it goes inside the if statement, it never executes the line but always skips it. I have no clue why this would happen. When i put “addOnScreenDebugMessage” at the line before the function call, inside the if statement, it will execute. Next it still skips the line …setDestroyed(true)
Any ideas?
MCX292
(MCX292)
September 7, 2019, 11:31am
2
I think you may have defeated the iterator functionality within TArray.
Try:
for(auto&& tankSpawn : tankSpawns)
Amneri
(Amneri)
September 7, 2019, 12:40pm
3
The problem is your undestanding of C++.
The line
for (FTankSpawn tankSpawn : tankSpawns)
Actually creates a copy of each FTankSpawn
. So when you call
tankSpawn.setDestroyed(true);
You’re modifying a copy and not the actual struct.
What you should do is using and index to get your struct :
for (int i = 0; i < tankSpawns.Num(); ++i)
{
if (tankSpawns[i].getLocation() == spawnLocation)
{
tankSpawns[i].setDestroyed(true);
}
}
Or use a reference with your range-based loop:
for (FTankSpawn& tankSpawn : tankSpawns)
{
if (tankSpawn .getLocation() == spawnLocation)
{
tankSpawn.setDestroyed(true);
}
}
MCX292
(MCX292)
September 8, 2019, 12:09pm
4
The examples at the bottom of this link make it clear what the issue is. You need to access by reference, not by value:
CPP Reference - Ranged For Loops