###前提・実現したいこと
unityでゲームアプリを作っているのですが、他のファイルで作った関数が呼び出せません。
中身は、AppleかBomb(Tag名)がbasketと衝突したら、GetApple関数かGetBomb関数を呼んでUIに反映させるアプリです。
GameDirector.csにあるGetApple関数とGetBomb関数をBasketController.csで呼ぼうとしているのですが、エラーが出てしまいます。
色々試した結果、関数の呼び出しそのものがうまくいってないようです。
エラーメッセージ
NullReferenceException: Object reference not set to an instance of an object
BasketController.OnTriggerEnter (UnityEngine.Collider other) (at Assets/BasketController.cs:18)
###該当のソースコード
BasketController.csのソースコード
using UnityEngine;
using System.Collections;
public class BasketController : MonoBehaviour {
public AudioClip appleSE; public AudioClip bombSE; AudioSource aud; GameObject director; void Start () { this.director = GameObject.Find("GameDirector"); this.aud = GetComponent<AudioSource>(); } void OnTriggerEnter(Collider other) { if(other.gameObject.tag == "Apple") { this.director.GetComponent<GameDirector>().GetApple(); this.aud.PlayOneShot(this.appleSE); } else { this.director.GetComponent<GameDirector>().GetBomb(); this.aud.PlayOneShot(this.bombSE); } Destroy(other.gameObject); } // Update is called once per frame void Update () { if(Input.GetMouseButtonDown(0)) { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if(Physics.Raycast(ray, out hit, Mathf.Infinity)) { float x = Mathf.RoundToInt(hit.point.x); float z = Mathf.RoundToInt(hit.point.z); transform.position = new Vector3(x, 0.0f, z); } } }
}
GameDirector.csのソースコード
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class GameDirector : MonoBehaviour {
GameObject timerText; GameObject pointText; float time = 60.0f; int point = 0; public void GetApple() { this.point += 100; } public void GetBomb() { this.point /= 2; } // Use this for initialization void Start () { this.timerText = GameObject.Find("Time"); this.pointText = GameObject.Find("Point"); } // Update is called once per frame void Update () { this.time -= Time.deltaTime; this.timerText.GetComponent<Text>().text = this.time.ToString("F1"); this.pointText.GetComponent<Text>().text = this.point.ToString() + "point"; }
}
###試したこと
衝突判定まではうまくいっています。
エラーメッセージに表示されているのはthis.director.GetComponent<GameDirector>().GetApple();の部分ですが、bombと衝突したときもうまくいきません。
回答1件
あなたの回答
tips
プレビュー