Skip to content

Instantly share code, notes, and snippets.

@Eraile
Created October 15, 2024 04:59
Show Gist options
  • Save Eraile/08f969bc0169ee7e1935c923b11695aa to your computer and use it in GitHub Desktop.
Save Eraile/08f969bc0169ee7e1935c923b11695aa to your computer and use it in GitHub Desktop.
Editor script to toggle on/off the "UI" layer when switching Unity Editor's scene view perspective (2D to 3D)... To avoid the huge UI flying over your 3D work
using UnityEditor;
using UnityEngine;
[InitializeOnLoad]
public static class SceneViewUILayerToggle
{
// Define the UI layer's mask
private static readonly int uiLayerMask = 1 << LayerMask.NameToLayer("UI");
// Constructor to initialize the script
static SceneViewUILayerToggle()
{
// Subscribe to the SceneView.duringSceneGui event, which gets called every frame in the Scene view
SceneView.duringSceneGui += OnSceneGUI;
}
private static bool wasInitialized = false;
private static bool wasIn2DMode = true;
private static void OnSceneGUI(SceneView sceneView)
{
if (wasIn2DMode != sceneView.in2DMode || wasInitialized == false)
{
// Reset flags
wasInitialized = true;
wasIn2DMode = sceneView.in2DMode;
// Update view
{
// Check if the scene view is in 2D mode
if (sceneView.in2DMode)
{
// If in 2D mode, make sure the UI layer is visible
SetLayerVisibility(sceneView, true);
}
else
{
// If not in 2D mode (i.e., 3D mode), make sure the UI layer is hidden
SetLayerVisibility(sceneView, false);
}
}
}
}
private static void SetLayerVisibility(SceneView sceneView, bool showUILayer)
{
// Get the current scene view layer mask
int currentMask = Tools.visibleLayers;
// If we want to show the UI layer
if (showUILayer)
{
// Add the UI layer to the mask if it's not already visible
Tools.visibleLayers = currentMask | uiLayerMask;
}
else
{
// Remove the UI layer from the mask if it's visible
Tools.visibleLayers = currentMask & ~uiLayerMask;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment