前提・実現したいこと
一番近いターゲットの方向へ移動。
それを破壊した後、次に近いターゲットへの接近。
ここに質問の内容を詳しく書いてください。
http://beatdjam.hatenablog.com/entry/2014/10/22/032751
上記サイトを参考にして、Unity2Dにて一番近いenemyへ接近するという機能を実装しようとしています。
一匹目のenemyに接近するのはうまくいくのですが、それを破壊した後、次の最も近いenemyへターゲットを移すことができていません。
おそらく、2Dなので敵位置の取得をLookAtの代わりで補っている部分が問題なのだろうとは思うのですが、どうすればうまく修正できるのかがわかりません。
発生している問題・エラーメッセージ
MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
該当のソースコード
C#
1using System.Collections; 2using System.Collections.Generic; 3using UnityEngine; 4 5public class Ally2 : MonoBehaviour { 6 7 Chara chara; 8 Rigidbody2D rd; 9 private GameObject nearEnemy; 10 private float seachTime = 0; 11 12 IEnumerator Start () { 13 nearEnemy = searchTag(gameObject,"Enemy"); 14 chara = GetComponent<Chara> (); 15 rd = GetComponent<Rigidbody2D> (); 16 17 while (true) { 18 Instantiate (bullet, AttackPos); 19 yield return new WaitForSeconds (AttackDelay); 20 } 21 } 22 23 void Update () { 24 seachTime = Time.deltaTime; 25 if (seachTime >= 1.0f) { 26 nearEnemy = searchTag (gameObject, "Enemy"); 27 seachTime = 0; 28 } 29 // 30 Vector3 diff = (nearEnemy.transform.position - this.transform.position); 31 this.transform.rotation = Quaternion.FromToRotation (Vector3.right,diff); 32 33 var v = new Vector2 (1.0f*Time.deltaTime, rd.velocity.y) * chara.Speed; 34 transform.Translate (v); 35 } 36 37 GameObject searchTag(GameObject nowEnemy,string tagName){ 38 float tmpDis = 0; 39 float nearDis = 0; 40 GameObject targetObj = null; 41 42 foreach (GameObject obs in GameObject.FindGameObjectsWithTag(tagName)) { 43 tmpDis = Vector2.Distance (obs.transform.position, nowEnemy.transform.position); 44 45 if (nearDis == 0 || nearDis > tmpDis) { 46 nearDis = tmpDis; 47 targetObj = obs; 48 } 49 } 50 return targetObj; 51 } 52}
試したこと
LookAtの代わりは下記サイトを参考にしました。
http://karaagedigital.hatenablog.jp/entry/2016/09/11/192600
補足情報(FW/ツールのバージョンなど)
よろしくお願いします。
回答2件
あなたの回答
tips
プレビュー