-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
CameraViewportRect.cs
104 lines (91 loc) · 2.73 KB
/
CameraViewportRect.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
using UnityEngine;
namespace Gilzoide.CameraViewportRect
{
[RequireComponent(typeof(RectTransform)), ExecuteAlways]
public class CameraViewportRect : MonoBehaviour
{
[Tooltip("Target Camera")]
[SerializeField] protected Camera _camera;
[Tooltip("Toggle Camera.enabled when this script gets enabled/disabled")]
public bool ToggleCameraEnabled = true;
public Camera Camera
{
get => _camera;
set
{
_camera = value;
if (isActiveAndEnabled)
{
RefreshCameraRect();
}
}
}
protected Canvas _canvas;
protected readonly Vector3[] _worldCorners = new Vector3[4];
public void RefreshCameraRect()
{
if (Camera && _canvas)
{
Camera.pixelRect = GetScreenRect();
}
}
protected virtual void Update()
{
if (transform.hasChanged)
{
transform.hasChanged = false;
RefreshCameraRect();
}
}
protected virtual void OnEnable()
{
_canvas = FindRootCanvas();
if (ToggleCameraEnabled && Camera)
{
Camera.enabled = true;
}
}
protected virtual void OnDisable()
{
if (ToggleCameraEnabled && Camera)
{
Camera.enabled = false;
}
}
protected virtual void OnTransformParentChanged()
{
if (isActiveAndEnabled)
{
_canvas = FindRootCanvas();
RefreshCameraRect();
}
}
#if UNITY_EDITOR
protected virtual void OnValidate()
{
if (isActiveAndEnabled)
{
RefreshCameraRect();
}
}
#endif
protected Rect GetScreenRect()
{
((RectTransform) transform).GetWorldCorners(_worldCorners);
Vector3 bottomLeft = _worldCorners[0];
Vector3 topRight = _worldCorners[2];
if (_canvas.renderMode == RenderMode.ScreenSpaceCamera && _canvas.worldCamera != null)
{
Camera camera = _canvas.worldCamera;
bottomLeft = camera.WorldToScreenPoint(bottomLeft);
topRight = camera.WorldToScreenPoint(topRight);
}
return Rect.MinMaxRect(bottomLeft.x, bottomLeft.y, topRight.x, topRight.y);
}
protected Canvas FindRootCanvas()
{
Canvas canvas = GetComponentInParent<Canvas>();
return canvas != null ? canvas.rootCanvas : null;
}
}
}