回答編集履歴

1

Camera.main削減版

2018/11/15 21:25

投稿

Bongo
Bongo

スコア10807

test CHANGED
@@ -5,3 +5,81 @@
5
5
 
6
6
 
7
7
  参考:[【Unity】スクリプトからMain Cameraを取得するのは簡単だよ](https://tech.pjin.jp/blog/2018/01/31/unity_get-main-camera/)
8
+
9
+
10
+
11
+ #追記
12
+
13
+ リファレンスによると`Camera.main`は一見ただの変数のように見えますが、内部的に[FindGameObjectsWithTag](https://docs.unity3d.com/ja/current/ScriptReference/GameObject.FindGameObjectsWithTag.html)を使っているプロパティだそうです。
14
+
15
+
16
+
17
+ Unityでのセオリーとして、[Update](https://docs.unity3d.com/ja/current/ScriptReference/MonoBehaviour.Update.html)や、今回使っている[OnMouseDrag](https://docs.unity3d.com/ja/current/ScriptReference/MonoBehaviour.OnMouseDrag.html)のような高頻度で実行されるメソッド中でFind系メソッドを乱発するな...とよく言われますが、それに従うと下記のように[OnMouseDown](https://docs.unity3d.com/ja/current/ScriptReference/MonoBehaviour.OnMouseDown.html)で(あるいは[Awake](https://docs.unity3d.com/ja/current/ScriptReference/MonoBehaviour.Awake.html)、[Start](https://docs.unity3d.com/ja/current/ScriptReference/MonoBehaviour.Start.html)などで)一度だけ取得する方が望ましいかもしれません。
18
+
19
+
20
+
21
+ ```C#
22
+
23
+ private Vector3 screenPoint;
24
+
25
+ private Vector3 offset;
26
+
27
+ private Camera mainCamera;
28
+
29
+
30
+
31
+ void OnMouseDown()
32
+
33
+ {
34
+
35
+ mainCamera = Camera.main;
36
+
37
+
38
+
39
+ screenPoint = mainCamera.WorldToScreenPoint(transform.position);
40
+
41
+
42
+
43
+ float x = Input.mousePosition.x;
44
+
45
+ float y = Input.mousePosition.y;
46
+
47
+
48
+
49
+ offset = transform.position - mainCamera.ScreenToWorldPoint(new Vector3(x, y, screenPoint.z));
50
+
51
+ }
52
+
53
+
54
+
55
+ void OnMouseDrag()
56
+
57
+ {
58
+
59
+ float x = Input.mousePosition.x;
60
+
61
+ float y = Input.mousePosition.y;
62
+
63
+
64
+
65
+ Debug.Log(x.ToString() + " - " + y.ToString());
66
+
67
+
68
+
69
+ Vector3 currentScreenPoint = new Vector3(x, y, screenPoint.z);
70
+
71
+
72
+
73
+ Vector3 currentPosition = mainCamera.ScreenToWorldPoint(currentScreenPoint) + offset;
74
+
75
+
76
+
77
+ transform.position = currentPosition;
78
+
79
+ }
80
+
81
+ ```
82
+
83
+
84
+
85
+ 参考:[Unite Europe 2017 - Squeezing Unity: Tips for raising performance](https://youtu.be/_wxitgdx-UI?t=546)