
Unityで2Dアクションゲームを作っていて、アイテムをステージ上のランダムな地上に生成させるスクリプトを書いたのですが、下記コードでNullReferenceが呼び出されて若干萎えてます。
collider.tagだと処理が重くなるからCompareTagに変えてやったというのに、何がいけないんだーッ!
…何を参照すれば解決するのか教えて下さると助かります。
c#
1public class Item : MonoBehaviour 2{ 3 /* public変数 */ 4 public float stageLeft, stageRight, stageHeight; 5 6 /* private変数 */ 7 [SerializeField] GameObject itemPref = null; 8 GameObject itemInstance; 9 Ray ray; 10 RaycastHit2D hit; 11 Vector2 tPos; 12 int count = 0; 13 float distance = 11.0f; 14 15 void Start() 16 { 17 while(count < 9) 18 { 19 tPos = new Vector2(Random.Range(stageLeft, stageRight), stageHeight); 20 ray = new Ray(tPos, -transform.up); 21 Debug.DrawLine(tPos, ray.direction * distance, Color.red); 22 23 if(Physics2D.Raycast(tPos, -transform.up)) 24 { 25 if (hit.collider.CompareTag("Ground")) //←ここでNullReferenceが起こる 26 { 27 itemInstance = Instantiate(itemPref) as GameObject; 28 itemInstance.name = itemPref.name; 29 itemInstance.transform.position = new Vector3(tPos.x, hit.collider.transform.position.y, -3.0f); 30 31 count++; 32 } 33 34 else 35 { 36 continue; 37 } 38 } 39 } 40 } 41 42}

> collider.tagだと処理が重くなるからCompareTagに変えてやったというのに、何がいけないんだーッ!
変更はその1点だけでしょうか。
また、「collider.tag」を使用し場合は発生しない、ということでよろしいでしょうか。

回答3件
あなたの回答
tips
プレビュー