For some reason, I’m getting a NullReferenceException error in my Die(). The specific error text from the Start Screen is:
“NullReferenceException: Object reference not set to an instance of an object PlayerController.Die() (at Assets/Scripts/PlayerController.cs:33)”
Can anyone help me figure out what I’ve done wrong? I’ve been looking at this for probably 2 hours and it looks exactly like the instructor’s code to me.
Here is the code, with the Die() bolded.:
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour
{
public float speed;
public float padding = 1f;
public GameObject projectile;
public float projectileSpeed;
public float firingRate = 0.2f;
public float health;
private float xmin;
private float xmax;
public AudioClip fireSound;
void OnTriggerEnter2D(Collider2D collider){
Projectile missile = collider.gameObject.GetComponent<Projectile>();
if(missile){
Debug.Log ("Player Collided with missile");
health -= missile.GetDamage();
missile.Hit();
if (health <= 0) {
Die();
}
}
}
void Die(){
LevelManager levelManager = GameObject.Find("LevelManager").GetComponent<LevelManager>();
levelManager.LoadLevel("End Screen");
Destroy(gameObject);
}
void Start(){
float distance = transform.position.z - Camera.main.transform.position.z;
Vector3 leftmost = Camera.main.ViewportToWorldPoint(new Vector3(0,0,distance));
Vector3 rightmost = Camera.main.ViewportToWorldPoint(new Vector3(1,0,distance));
xmin = leftmost.x + padding;
xmax = rightmost.x - padding;
}
void Fire(){
GameObject beam = Instantiate(projectile, transform.position, Quaternion.identity) as GameObject;
beam.rigidbody2D.velocity = new Vector3(0, projectileSpeed, 0);
AudioSource.PlayClipAtPoint(fireSound, transform.position);
}
void Update () {
if(Input.GetKeyDown(KeyCode.Space)){
InvokeRepeating("Fire", 0.0001f, firingRate);
}
if(Input.GetKeyUp(KeyCode.Space)){
CancelInvoke("Fire");
}
if(Input.GetKey(KeyCode.LeftArrow)){
transform.position += Vector3.left * speed * Time.deltaTime;
}else if (Input.GetKey(KeyCode.RightArrow)){
transform.position += Vector3.right * speed * Time.deltaTime;
}
// restrict the player to the gamespace
float newX = Mathf.Clamp(transform.position.x, xmin, xmax);
transform.position = new Vector3(newX, transform.position.y, transform.position.z);
}
}