Download

Obviously I'm missing something here with structs and arrays. Please Help!

Right now I just need to clear the array of structures and start adding components based on my grid. I’ve read through everything I could find and I cannot see where anyone is actually trying to SET any of their structure variables before adding them to the array. Everything I’m trying is failing. The array is specified as:



	UPROPERTY(BlueprintReadWrite, Category = "LevelGenerator")
	TArray<FGridTile> LevelTiles;


And I need to do something like this:



void ALevelGenerator::CreateWorld(int32 TilesX, int32 TilesY)
{
	//empty our array of tiles
	LevelTiles.Empty();

	//Generate a new array based on our current world size parameters
	for (int x = 0; x < TilesX; x++)
		for (int y = 0; y < TilesY; y++)
		{
			FGridTile newTile;
			newTile.CurrentIndex = (y*TilesX) + x;
			newTile.GridX = x;
			newTile.GridY = y;

			LevelTiles.AddUnique(newTile);
		}
}


I know this is a simple mistake. It’s just because I’m finding structure and TArray references and documentation to be sparse. Don’t get me wrong, there are great documents relating to structures, and great documents relating to arrays. But not much I can find relating to both and setting structure elements then adding those structures to the arrays. I’m sure I’m going to come up just as frustrated when I need to start accessing the data in the array.

Thanks!

Okay. Apparently you can’t use a structure with AddUnique. I just wanted the extra protection of the Unique functionality. Changed it to LevelTiles.Add(newTile); and it seems to work.

I’m assuming this is because AddUnique will probably look through your TArray of FGridTiles and try and compare your new one to any in the array. But because the code won’t know how to compare your FGridTiles, it won’t be able to use them with the AddUnique. You may be able to overload a comparison (==) function, but I’m not sure whether that would actually work.

The AddUnique() method uses the == comparison operator to compare with existing entries. You’ll need to define this operator for your struct if you want to use it for this. C++ structs do not have this generated by default.

Also, AddUnique() method does compare with existing entries. You really should not use it in your case since you know LevelTiles is empty before, and there is no chance of having non-unique entries. There will not be extra protection for you, but instead extra overhead when adding items due to the internal calls to Find().