#if UNITY_EDITOR
using UnityEditor;
using UnityEditor.SceneManagement;
#endif
using UnityEngine;

[RequireComponent(typeof(Camera))]
[ExecuteInEditMode]
public class MatchSceneViewTransform : MonoBehaviour
{
    [Tooltip("Limit the far clip plane, avoid render too much and cause GPU Overload")]
    public float farClipLimit = 4000f;

#if UNITY_EDITOR
    private void OnEnable()
    {
        EditorApplication.update += SyncWithSceneView;
    }

    private void OnDisable()
    {
        EditorApplication.update -= SyncWithSceneView;
    }

    void SyncWithSceneView()
    {
        if (SceneView.lastActiveSceneView != null)
        {
            Camera sceneCam = SceneView.lastActiveSceneView.camera;
            if (sceneCam != null)
            {
                Transform t = transform;
                t.position = sceneCam.transform.position;
                t.rotation = sceneCam.transform.rotation;

                Camera camera = GetComponent<Camera>();

                camera.nearClipPlane = sceneCam.nearClipPlane;
                camera.farClipPlane = Mathf.Min(sceneCam.farClipPlane, farClipLimit);
                camera.fieldOfView = sceneCam.fieldOfView;
                camera.orthographic = sceneCam.orthographic;
                camera.aspect = sceneCam.aspect;

                // Mark scene dirty if needed
                //if (!EditorApplication.isPlayingOrWillChangePlaymode)
                    //EditorSceneManager.MarkSceneDirty(gameObject.scene);
            }
        }
    }
#endif
}
