Download

How to correctly determine which instanced static mesh is under the cursor?

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:

Screenshot-OK.jpg
Screenshot-OK2.jpg

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:

Screenshot-ERROR.jpg
Screenshot-ERROR2.jpg

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?

Does result.GetComponent() return anything when you hover over the upper half of the cube?

Yes, it does as well correctly return the [FONT=courier new]UInstancedStaticMeshComponent. However, in the upper half of the cube the call to [FONT=courier new]meshComp->GetInstancesOverlappingSphere() as in the code above returns 0, so no mesh indices found at all.

For the records:
The index of the instanced static mesh under the cursor can be found in [FONT=courier new]FHitResult::Item, thus in [FONT=courier new]result.Item in my code above.
Thanks a lot to @DamirH for pointing that out!