###前提・実現したいこと
衝突したオブジェクトのスクリプトの変数を参照して、値を変えたい。
###発生している問題・エラーメッセージ
NULLだよというエラーがでてしまう。
NullReferenceException: Object reference not set to an instance of an object particle.OnParticleCollision (UnityEngine.GameObject other) (at Assets/Script/particle.cs:24)
###該当のソースコード
以下が参照したいスクリプトです。
C#
1using System.Collections; 2using System.Collections.Generic; 3using UnityEngine; 4 5public class enemyController : MonoBehaviour { 6 7 public GameObject character; 8 public GameObject p; 9 Vector3 target; 10 Animator animator; 11 float speed; 12 float dist; 13 public float life=3.0f; //参照したい変数 14 15 // Use this for initialization 16 void Start () { 17 animator = GetComponent<Animator> (); 18 } 19 20 // Update is called once per frame 21 void Update () { 22 23 transform.position = new Vector3 (transform.localPosition.x, transform.localPosition.y*20.0f*Time.deltaTime, transform.localPosition.z); 24 25 target.x = character.transform.localPosition.x; 26 target.y = character.transform.localPosition.y; 27 target.z = character.transform.localPosition.z; 28 transform.LookAt (new Vector3 (target.x, target.y, target.z)); 29 dist = Vector3.Distance (transform.position, character.transform.position); 30 31 if (dist > 1.0f && dist <= 5.0f) { 32 speed = 1.5f; 33 animator.SetBool ("Attack", false); 34 35 animator.SetBool ("Walk", true); 36 transform.position += transform.forward * speed * Time.deltaTime; 37 } else if (dist <= 1.0f) { 38 39 animator.SetBool ("Walk", false); 40 animator.SetBool ("Attack", true); 41 speed = 0.0f; 42 } else if (dist >= 5.0f) { 43 animator.SetBool ("Attack", false); 44 animator.SetBool ("Walk", false); 45 } 46 47 48 49 } 50 51 52 53 54 55 } 56 57
以下が参照させるスクリプトです。
C#
1using System.Collections; 2using System.Collections.Generic; 3using UnityEngine; 4 5public class particle : MonoBehaviour { 6 7 public GameObject[] target; 8 float dist; 9 10 // Use this for initialization 11 void Start () { 12 13 } 14 15 // Update is called once per frame 16 void Update () { 17 dist = Vector3.Distance (transform.localPosition, target[0].transform.localPosition); 18 } 19 20 void OnParticleCollision(GameObject other){ 21 22 if (dist <= 5.0f) { 23 24 other.GetComponent<enemyController> ().life -= 1; //参照して値を変える。 25 Debug.Log ("In"); 26 } 27 28 } 29} 30
どうしたら参照して値をかえることができるのかおしえてください。
宜しくお願い致します。
###補足情報(言語/FW/ツール等のバージョンなど)
Unity5.6.1
Bongoさんへ
dist = Vector3.Distance (transform.localPosition, target[0].transform.localPosition);
このtarget[0]には衝突させるオブジェクトが入っており、
if (dist <= 5.0f) のdistにはそのオブジェクトとの距離が入っているので、ほかのオブジェクトに衝突しても無視されるようになっています。
試してみても問題なく動作するため、ほかのオブジェクトとは関わっていません。
また、衝突させるオブジェクトにはenemyController.csがアタッチされているのでみつからない原因がわからないのです・・・。
ちなみに、反対にゲームオブジェクトにパーティクルシステムが衝突したのか判定する方法はありますか?
泥沼にはまっています・・・。
回答2件
あなたの回答
tips
プレビュー