teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

1

Camera.main削減版

2018/11/15 21:25

投稿

Bongo
Bongo

スコア10816

answer CHANGED
@@ -1,4 +1,43 @@
1
1
  ご提示のコードの中で`null`になりうる物となると[Camera.main](https://docs.unity3d.com/ja/current/ScriptReference/Camera-main.html)かと思います。
2
2
  タグが「MainCamera」のカメラが一つもないと`null`になりますので、タグをチェックしてみてはいかがでしょうか。
3
3
 
4
- 参考:[【Unity】スクリプトからMain Cameraを取得するのは簡単だよ](https://tech.pjin.jp/blog/2018/01/31/unity_get-main-camera/)
4
+ 参考:[【Unity】スクリプトからMain Cameraを取得するのは簡単だよ](https://tech.pjin.jp/blog/2018/01/31/unity_get-main-camera/)
5
+
6
+ #追記
7
+ リファレンスによると`Camera.main`は一見ただの変数のように見えますが、内部的に[FindGameObjectsWithTag](https://docs.unity3d.com/ja/current/ScriptReference/GameObject.FindGameObjectsWithTag.html)を使っているプロパティだそうです。
8
+
9
+ 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)などで)一度だけ取得する方が望ましいかもしれません。
10
+
11
+ ```C#
12
+ private Vector3 screenPoint;
13
+ private Vector3 offset;
14
+ private Camera mainCamera;
15
+
16
+ void OnMouseDown()
17
+ {
18
+ mainCamera = Camera.main;
19
+
20
+ screenPoint = mainCamera.WorldToScreenPoint(transform.position);
21
+
22
+ float x = Input.mousePosition.x;
23
+ float y = Input.mousePosition.y;
24
+
25
+ offset = transform.position - mainCamera.ScreenToWorldPoint(new Vector3(x, y, screenPoint.z));
26
+ }
27
+
28
+ void OnMouseDrag()
29
+ {
30
+ float x = Input.mousePosition.x;
31
+ float y = Input.mousePosition.y;
32
+
33
+ Debug.Log(x.ToString() + " - " + y.ToString());
34
+
35
+ Vector3 currentScreenPoint = new Vector3(x, y, screenPoint.z);
36
+
37
+ Vector3 currentPosition = mainCamera.ScreenToWorldPoint(currentScreenPoint) + offset;
38
+
39
+ transform.position = currentPosition;
40
+ }
41
+ ```
42
+
43
+ 参考:[Unite Europe 2017 - Squeezing Unity: Tips for raising performance](https://youtu.be/_wxitgdx-UI?t=546)