Hey all,
I am more used to working in languages where I don’t have to worry about memory management and pointers and what not, so I am sure this is just me doing something stupid, but I am not sure what.
In a setup routine I am creating instances of a UObject based class, and sticking a pointer to each into a TMap. Then later on I am iterating through the TMap to do things with them. However when I get the instance out of the TMap later, the data inside it is not correct!
Here is my setup
void AHexGridActor::CreateGrid()
{
if (!DirtyCreate)
return;
UE_LOG(LogTemp, Display, TEXT("CreateGrid"));
DirtyCreate = false;
Tiles.Reserve(Radius * Radius * Radius);
int32 tileCount = 0;
for (int32 i = -Radius; i <= Radius; i++)
{
for (int32 j = -Radius; j <= Radius; j++)
{
FString tileName = FString::Printf(TEXT("HexTile_%d"), tileCount++);
UHexTile* newTile = NewObject<UHexTile>(this, UHexTile::StaticClass(), *tileName);
tileCount++;
if (newTile == nullptr)
{
UE_LOG(LogTemp, Error, TEXT("Failed to create HexTile object"))
}
else
{
FString tileAddress = FString::Printf(TEXT("%d,%d"), i, j);
newTile->Position = FHexCoordinate{ 0, 0 };
newTile->Transform = FTransform(FVector(100,10,50));
newTile->Transform.NormalizeRotation();
newTile->Dirty = true;
newTile->Valid = true;
newTile->OnCreateTile();
UE_LOG(LogTemp, Display, TEXT("Tile's transform: %s"), *newTile->Transform.ToString());
if (newTile->Valid)
{
UE_LOG(LogTemp, Warning, TEXT("Skipping tile, as is marked invalid"));
Tiles.Add(tileAddress, newTile);
}
}
}
}
DirtyDraw = true;
}
And later usage
void AHexGridActor::DrawGrid()
{
for (auto& Entry : Tiles)
{
UHexTile* tile = Entry.Value;
/*tile->OnDrawTile();*/
UStaticMesh* tileMesh = tile->Mesh;
if (tileMesh != nullptr)
{
if (TileMeshInstances.Contains(tileMesh))
{
UHierarchicalInstancedStaticMeshComponent* hism = TileMeshInstances[tileMesh];
hism->AddInstance(tile->Transform);
}
else
{
int32 hismCount = TileMeshInstances.Num();
FString hismName = FString::Printf(TEXT("TileMeshInstance_%d"), hismCount);
UHierarchicalInstancedStaticMeshComponent* hism = NewObject<UHierarchicalInstancedStaticMeshComponent>(this, UHierarchicalInstancedStaticMeshComponent::StaticClass(), *hismName);
hism->RegisterComponent();
hism->AttachTo(RootComponent);
UE_LOG(LogTemp, Display, TEXT("Using transform for instance: %s"), *tile->Transform.ToString());
hism->AddInstance(tile->Transform);
TileMeshInstances.Add(tileMesh, hism);
}
}
}
}