UInstancedStaticMeshComponent->GetInstanceCount() bug

I’m currently working on generating a building by generating a bunch of rectangular rooms and attaching them to eachothers sides. I’ve gotten that to work, so now I’ve gone about adding walls to these rooms, via UInstancedStaticMeshComponents on each rectangle.

In my attempts to remove duplicate walls in the same tiles (i.e., duplicate walls for when a rectangle is attached to another rectangle), I’m doing a for loop to get each instance of my InstancedStaticMesh on each rectangle, checking if any overlap and then removing said instances. As such, I have the following code:

	for (int a = 0; a < WExtStraightMesh->GetInstanceCount() - 1; ++a)
	{
		UE_LOG(LogTemp, Warning, TEXT("This works!"))

		/*for (int b = 0; b < ParentRect->WExtStraightMesh->GetInstanceCount() - 1; ++b) 
		{
            //But this for loop line causes a crash on play!!

			FTransform A; WExtStraightMesh->GetInstanceTransform(a, A); FVector AV = A.GetTranslation();
			FTransform B; ParentRect->WExtStraightMesh->GetInstanceTransform(b, B); FVector BV = B.GetTranslation();
			if (AV == BV)
			{
				WExtStraightMesh->RemoveInstance(a);
				ParentRect->WExtStraightMesh->RemoveInstance(b);
			}
		}*/
	}

WExtStraightMesh is the class’ InstancedStaticMeshComponent (for straight exterior walls), and ParentRect is a pointer to the “parent” Rect class that we are attached to. I imagine the problem lies somewhere within the pointer; but what is the solution?

Please familiarize yourself with a debugger, it will save you a lot of time in the long run. I can’t tell you why your code crashes, but I can point out a flaw in your logic, you’re iterating through an array front to back and removing items as you go, this invalidates all indices you haven’t iterated through yet. You should iterate through the instances in reverse order, that way you won’t invalidate indices you haven’t iterated through yet.

I get what your saying about the logic, thanks! Fixed it :slight_smile:

have you been able to make arrays/references of instancedstaticmesh instances? I can .RemoveInstance by index, but everything else crashes…