Skip to content

Instantly share code, notes, and snippets.

@baba-s
Created August 25, 2018 10:00
Show Gist options
  • Save baba-s/a015b3347dc7ac11ae6b661184cf1a06 to your computer and use it in GitHub Desktop.
Save baba-s/a015b3347dc7ac11ae6b661184cf1a06 to your computer and use it in GitHub Desktop.
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;
using UnityEngine.SceneManagement;
[InitializeOnLoad]
public static class SceneViewContextMenu
{
private static Vector3[] corners = new Vector3[ 4 ];
static SceneViewContextMenu()
{
SceneView.onSceneGUIDelegate += OnSceneGUI;
}
private static void OnSceneGUI( SceneView sceneView )
{
var e = Event.current;
if ( e == null ) return;
if ( e.type != EventType.MouseUp ) return;
if ( e.button != 1 ) return;
e.Use();
ShowSpriteSelectionMenu( e.mousePosition );
}
private static void ShowSpriteSelectionMenu( Vector2 screenPos )
{
var groups = SceneViewRaycast( screenPos )
.GroupBy( c => c.gameObject.scene.name )
.ToArray()
;
var isOneScene = GetAllScenes().Count( c => c.isLoaded ) <= 1;
var menu = new GenericMenu();
var nameTable = new Dictionary<string, int>();
foreach ( var group in groups )
{
foreach ( var n in group )
{
var name = n.name;
var sceneName = n.gameObject.scene.name;
var nameWithSceneName = sceneName + "/" + name;
var isSameName = nameTable.ContainsKey( nameWithSceneName );
var text = isOneScene ? name : nameWithSceneName;
if ( isSameName )
{
var count = nameTable[ nameWithSceneName ]++;
text += " [" + count.ToString() + "]";
}
var content = new GUIContent( text );
menu.AddItem( content, false, () => OnSelect( n ) );
if ( !isSameName )
{
nameTable.Add( nameWithSceneName, 1 );
}
}
}
menu.ShowAsContext();
}
private static void OnSelect( RectTransform rectTransform )
{
Selection.activeTransform = rectTransform;
EditorGUIUtility.PingObject( rectTransform );
}
private static IEnumerable<RectTransform> SceneViewRaycast( Vector2 mousePos )
{
return GetAllScenes()
.Where( c => c.isLoaded )
.SelectMany( c => c.GetRootGameObjects() )
.Where( c => c.activeInHierarchy )
.SelectMany( c => c.GetComponentsInChildren<RectTransform>() )
.Where( c =>
{
c.GetWorldCorners( corners );
return NGUIEditorTools.SceneViewDistanceToRectangle( corners, mousePos ) == 0;
} )
;
}
private static IEnumerable<Scene> GetAllScenes()
{
for ( int i = 0; i < SceneManager.sceneCount; i++ )
{
yield return SceneManager.GetSceneAt( i );
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment