前提・実現したいこと
「タップした座標を取得してその座標に向かってオブジェクト(イガグリ)に力を加えて発射し、的に当たったら張り付く」という物を作りたいのですが、イガグリのインスタンスを生成した瞬間「NullReferenceException: Object reference not set to an instance of an object」とエラーが出てしまいます。(ちなみにそのとき生成されたインスタンスは、力がかかっていないようでRigidbodyの影響で地面に落ちてしまいます)
発生している問題・エラーメッセージ
NullReferenceException: Object reference not set to an instance of an object IgaguriGenerator.Update () (at Assets/IgaguriGenerator.cs:15)
該当のソースコード
C#
1using System.Collections; 2using System.Collections.Generic; 3using UnityEngine; 4 5public class IgaguriController : MonoBehaviour { 6 7 public void Shoot(Vector3 dir){ 8 //力をかける 9 GetComponent<Rigidbody>().AddForce(dir); 10 } 11 12 void OnCollisionEnter(Collision other){ 13 //的に接着 14 GetComponent<Rigidbody>().isKinematic = true; 15 //エフェクトの再生 16 GetComponent<ParticleSystem>().Play(); 17 } 18} 19
C#
1using System.Collections; 2using System.Collections.Generic; 3using UnityEngine; 4 5public class IgaguriGenerator : MonoBehaviour { 6 7 public GameObject igaguriPrefab; 8 9 void Update () { 10 if (Input.GetMouseButtonDown(0)){ 11 //インスタンスを生成 12 GameObject igaguri = Instantiate(igaguriPrefab) as GameObject; 13 14 //タップ座標をrayに渡す 15 Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); 16 //変数にカメラからタップ座標までの長さを代入 17 Vector3 worldDir = ray.direction; 18 //normalizedメゾッドで長さ1のベクトルにして2000の力をかける 19 igaguri.GetComponent<IgaguriController>().Shoot(worldDir.normalized * 2000); 20 } 21 } 22} 23
補足情報(FW/ツールのバージョンなど)
バージョンはUnity 2018.2.7f1 Personalです。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/10/16 10:03