Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save CSaratakij/696a8ab6c4c6c8611ed96492920a3579 to your computer and use it in GitHub Desktop.
Save CSaratakij/696a8ab6c4c6c8611ed96492920a3579 to your computer and use it in GitHub Desktop.
Custom Editor Toolbar to make SceneView follow game play camera (Current "main camera")
using UnityEngine;
using UnityEditor;
using UnityEditor.Overlays;
using UnityEditor.Toolbars;
#if !UNITY_EDITOR
#error This script must be placed under "Editor/" directory.
#endif
[Overlay(typeof(SceneView), "CustomToolbar/SceneViewFollowGamePlayCameraOverlay")]
public class SceneViewFollowGamePlayCameraOverlay : ToolbarOverlay
{
SceneViewFollowGamePlayCameraOverlay() : base(
SceneViewFollowGamePlayCameraToolbarToggle.ID
)
{}
}
[EditorToolbarElement(ID, typeof(SceneView))]
public class SceneViewFollowGamePlayCameraToolbarToggle : EditorToolbarToggle, IAccessContainerWindow
{
public const string ID = "CustomToolbar/SceneViewFollowGamePlayCameraToolbarToggle";
public static readonly string KEY_TOGGLE_STATUS = $"{ID}_ToggleStatus";
public EditorWindow containerWindow { get; set; }
private Camera gameplayCamera;
public SceneViewFollowGamePlayCameraToolbarToggle()
{
icon = EditorGUIUtility.FindTexture("d_UnityEditor.GameView");
tooltip = "Follow Game Play Camera";
value = EditorPrefs.GetBool(KEY_TOGGLE_STATUS, false);
SceneView.duringSceneGui += OnSceneGUI;
}
private void OnSceneGUI(SceneView view)
{
if (EditorApplication.isPlaying)
{
FollowGamePlayCamera(view);
}
}
protected override void ToggleValue()
{
base.ToggleValue();
EditorPrefs.SetBool(KEY_TOGGLE_STATUS, value);
}
private void FollowGamePlayCamera(SceneView view)
{
bool isValid = (view == containerWindow) && value;
if (!isValid)
{
return;
}
if (gameplayCamera == null)
{
gameplayCamera = Camera.main;
}
if (gameplayCamera)
{
var target = gameplayCamera.transform;
view.AlignViewToObject(target);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment