Skip to content

Instantly share code, notes, and snippets.

@pointcache
Created February 17, 2022 04:12
Show Gist options
  • Save pointcache/70cfa9af62030d1b6296980514023d13 to your computer and use it in GitHub Desktop.
Save pointcache/70cfa9af62030d1b6296980514023d13 to your computer and use it in GitHub Desktop.
Go back to previously selected object
[InitializeOnLoad]
public static class GoBackSelection
{
static GoBackSelection()
{
Selection.selectionChanged -= HandleSelectionChange;
Selection.selectionChanged += HandleSelectionChange;
HandleSelectionChange();
}
private static Stack<UnityEngine.Object> stack = new Stack<UnityEngine.Object>();
private static bool IgnoreSelection;
private static void HandleSelectionChange()
{
if(IgnoreSelection)
{
IgnoreSelection = false;
return;
}
stack.Push(Selection.activeObject);
}
[MenuItem("Edit/GoBack")]
public static void GoBackMenuItem()
{
GoBack();
}
public static void GoBack()
{
if (stack.Count == 0)
{
return;
}
if(stack.Count == 1)
{
var obj = stack.Peek();
if(obj != Selection.activeObject)
{
IgnoreSelection = true;
Selection.activeObject = stack.Peek();
}
}
else
{
stack.Pop();
var obj = stack.Peek();
if (obj && obj != Selection.activeObject)
{
IgnoreSelection = true;
Selection.activeObject = obj;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment