I have created a new actor that includes an [FONT=courier new]UInstancedStaticMeshComponent.
In this actor I add one single instanced static mesh in [FONT=courier new]BeginPlay() like this:
FTransform trans;
trans.SetLocation(FVector(ForceInitToZero));
TempInstancedMeshComp->AddInstanceWorldSpace(trans);
Now in the player controller I want to know every time the player hovers the mouse over that instanced static mesh.
I do this with the following code:
FHitResult result(ForceInit);
GetHitResultUnderCursor(ECollisionChannel::ECC_Visibility, true, result);
UPrimitiveComponent* comp = result.GetComponent();
if (comp && comp->GetName() == "InstancedMeshes") // Name of the UInstancedStaticMeshComponent
{
UInstancedStaticMeshComponent* meshComp = Cast<UInstancedStaticMeshComponent>(comp);
if (meshComp)
{
DrawDebugSphere(GetWorld(), result.Location, 2.0f, 25, FColor::Orange);
TArray<int32> instances = meshComp->GetInstancesOverlappingSphere(result.Location, 0.0001f, true);
if (instances.Num() > 0)
{
GEngine->AddOnScreenDebugMessage(-1, 0.1f, FColor::Yellow, FString::Printf(
TEXT("%d (of %d) at loc. %s"), instances[0], instances.Num(), *result.Location.ToString()));
}
}
}
This code adds a small debug sphere to the location under the cursor when it hovers over the instanced mesh.
And it also prints out which mesh index it is:
However, this does not always work. In my simple example it seems to work only when the cursor is over the lower half of the cube.
But whenever I move the cursor upwards, even though it is sitll over the cube, my code does not recognize this:
Note the small debug sphere which is correcly rendered under the cursor on the cube, but nothing is printed.
So the call to [FONT=courier new]GetInstancesOverlappingSphere() does not return the correct mesh instance in all cases.
Any ideas what I am doing wrong here?
Or is this even a bug in the UE4 code?