Responding to Unreal Engine Editor Selection (C++)
Tested in Unreal Engine version 4.27

Problem
Solution
Bonus: Responding to Actor Moved in Editor
Conclusion

Last updated
Tested in Unreal Engine version 4.27


Last updated
#include "Engine/Selection.h"
AExampleActor::AExampleActor()
{
#if WITH_EDITOR
// Broadcast whenever the editor selection changes (viewport or world
// outliner)
USelection::SelectionChangedEvent.AddUObject(this,
&AExampleActor::OnSelectionChanged);
#endif
}#if WITH_EDITOR
void OnSelectionChanged(UObject* NewSelection);
bool bSelectedInEditor;
#endifvoid AExampleActor::OnSelectionChanged(UObject* NewSelection)
{
TArray<AExampleActor*> SelectedExampleActors;
// Get AExampleActors from the selection
USelection* Selection = Cast<USelection>(NewSelection);
if (Selection != nullptr)
{
Selection->GetSelectedObjects<AExampleActor>(
SelectedExampleActors);
}
// Search the selection for this actor
for (AExampleActor* SelectedExampleActor : SelectedExampleActors)
{
// If our actor is in the selection and was not previously
// selected, then this selection change marks the actor
// being selected
if (SelectedExampleActor == this && !bSelectedInEditor)
{
// Respond to this actor being selected
bSelectedInEditor = true;
}
}
// If our record shows our actor is selected, but IsSelected() is false,
// this selection change marks the actor being deselected
if (bSelectedInEditor && !IsSelected())
{
// Respond to this actor being deselected
bSelectedInEditor = false;
}
}
#endif#if WITH_EDITOR
virtual void PostEditMove(bool bFinished) override;
#endif#if WITH_EDITOR
void AExampleActor::PostEditMove(bool bFinished)
{
Super::PostEditMove(bFinished);
if (bFinished)
{
// finished moving (e.g. let go of mouse click)
}
else
{
// move in progress (e.g. user dragging mouse)
}
}
#endif