我在Unity自己的教程的帮助下制作Flappy Bird,并设法一直到视频,在那里他展示了如何添加游戏控制器。一切都很好,但我似乎无法弄清楚如何摆脱这个错误:
NullReferenceException:未将对象引用设置为对象的实例 Bird.OnCollisionEnter2D()(在Assets / Scripts / Bird.cs:37)
这是GameController的代码:
using UnityEngine;
using System.Collections;
public class GameControl : MonoBehaviour
{
public static GameControl instance;
public GameObject gameOverText;
public bool gameOver = false;
// Use this for initialization
void Awake ()
{
if (instance == null) {
instance = this;
}
else if (instance != this)
{
Destroy (gameObject);
}
}
// Update is called once per frame
void Update () {
}
public void BirdDied()
{
gameOverText.SetActive (true);
gameOver = true;
}
}
这是Bird.cs:
using UnityEngine;
using System.Collections;
public class Bird : MonoBehaviour {
public float upForce = 200f;
private bool isDead = false;
private Rigidbody2D rb2d;
private Animator anim;
void Start ()
{
rb2d = GetComponent<Rigidbody2D> ();
anim = GetComponent<Animator> ();
}
void Update ()
{
if (isDead == false)
{
if (Input.GetMouseButtonDown (0))
{
rb2d.velocity = Vector2.zero;
rb2d.AddForce (new Vector2 (0, upForce));
anim.SetTrigger ("Flap");
}
}
}
void OnCollisionEnter2D ()
{
isDead = true;
anim.SetTrigger ("Die");
GameControl.instance.BirdDied ();
}
}
我设法让它工作,我不确定我到底做了什么,但我在代码中没有改变任何内容。