How do you fix NullReferenceException: Object reference not set to an instance of an object... errors?
Hello. I am trying to create a 2d video game where the player can turn right and left using arrow keys, and shoots a harpoon when the space bar is pressed. However, I can't figure out how to make the harpoon shoot into the direction the player is facing because I keep getting this error-
NullReferenceException: Object reference not set to an instance of an object
playerMove.FixedUpdate () (at Assets/Scripts/playerMove.cs:62)
What I want to know is
What is NullReferenceExeption?
How do I fix my code to work?
Thanks in advance- George :)
Here is the code I used-
playerMove.cs (script)
using UnityEngine;
using System.Collections;
public class playerMove : MonoBehaviour {
// All Variables
public float speed = 10;
private Rigidbody2D rigidBody2D;
private GameObject harpoon_00001;
private bool facingRight = true;
void Awake () {
rigidBody2D = GetComponent<Rigidbody2D>();
harpoon_00001 = GameObject.Find("harpoon_00001");
}
void Update () {
if (Input.GetKeyDown(KeyCode.LeftArrow) && !facingRight) {
Flip();
}
if (Input.GetKeyDown(KeyCode.RightArrow) && facingRight) {
Flip();
}
}
void Flip () {
facingRight = !facingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
void FixedUpdate () {
float xMove = Input.GetAxis("Horizontal");
float yMove = Input.GetAxis("Vertical");
float xSpeed = xMove * speed;
float ySpeed = yMove * speed;
Vector2 newVelocity = new Vector2(xSpeed, ySpeed);
rigidBody2D.velocity = newVelocity;
if (Input.GetKeyDown("space")) {
GetComponent<AudioSource>().Play();
harpoonScript harpoon = Instantiate(harpoon_00001,transform.position, Quaternion.identity) as harpoonScript;
// Assuming harpoon prefab already facing to right
if (facingRight) {
// Maybe, not required
harpoon.transform.eulerAngles = new Vector3(0f, 0f, 180f); // Face backward
Vector3 theScale = harpoon.transform.localScale;
theScale.y *= -1;
harpoon.transform.localScale = theScale; // Flip on y axis
}
}
}
}
harpoonScript.cs (script)
using UnityEngine;
using System.Collections;
public class harpoonScript : MonoBehaviour {
// Public variable
public int speed = 6;
private Rigidbody2D r2d;
// Function called once when the bullet is created
void Start () {
// Get the rigidbody component
r2d = GetComponent<Rigidbody2D>();
// Make the bullet move upward
float ySpeed = 0;
float xSpeed = -8;
Vector2 newVelocity = new Vector2(xSpeed, ySpeed);
r2d.velocity = newVelocity;
}
void OnTriggerEnter2D(Collider2D other) //hero hits side of enemy
{
Destroy(other.gameObject.GetComponent<Collider2D>()); //Remove collider to avoid audio replaying
other.gameObject.GetComponent<Renderer>().enabled = false; //Make object invisible
Destroy(other.gameObject, 0.626f); //Destroy object when audio is done playing, destroying it before will cause the audio to stop
}
}
Answer by Jessespike · Jul 05, 2016 at 05:17 PM
A null reference means just that. A reference is null. For example:
harpoon_00001 = GameObject.Find("harpoon_00001");
in this line, it's trying to find an object and store a reference of it. If the GameObject is found, then the reference will be stored in harpoon_00001. If no GameObject can be found found, then the reference (harpoon00001) will be null. because it couldn't be found or doesn't exist.
harpoon_00001 = GameObject.Find("harpoon_00001");
if (harpoon_00001 == null) {
Debug.Log("Unable to find GameObject, reference is null");
} else {
Debug.Log("GameObject found, reference is not null");
}
For your code and problem specifically, I'm not sure. It could be several spots. Either the GameObject.Find is failing to find to find the harpoon which will cause the Instantiate to fail. Or what could be happening is the harpoon is destroying itself via OnTriggerEnter2D immediately after it is instantiated, GameObjects that have been destroyed will equal null. Best thing to do, is to add Debug.Logs and verify your code. Such as, add one to OnTriggerEnter2D, so you know when it is being destroyed.
I added in the Debug.Logs in several places (the place where space is pressed in the player$$anonymous$$ove script, in the onTriggerEnter2D part in harpoonScript, and in the Start function of the player$$anonymous$$ove script). The funny thing is, that when the game starts, the console says-
GameObject found, reference is not null UnityEngine.Debug:Log(Object) player$$anonymous$$ove:Awake() (at Assets/Scripts/player$$anonymous$$ove.cs:19)
GameObject found, reference is not null UnityEngine.Debug:Log(Object) harpoonScript:OnTriggerEnter2D(Collider2D) (at Assets/Scripts/harpoonScript.cs:29)
GameObject found, reference is not null UnityEngine.Debug:Log(Object) player$$anonymous$$ove:FixedUpdate() (at Assets/Scripts/player$$anonymous$$ove.cs:65)
GameObject found, reference is not null UnityEngine.Debug:Log(Object) player$$anonymous$$ove:FixedUpdate() (at Assets/Scripts/player$$anonymous$$ove.cs:72)
When you press space, and the character is facing left(---->this way---->) , the console says this-
GameObject found, reference is not null UnityEngine.Debug:Log(Object) player$$anonymous$$ove:FixedUpdate() (at Assets/Scripts/player$$anonymous$$ove.cs:65)
When you press space, and the character is facing right (<----this way<----) the default position, the console says this-
GameObject found, reference is not null UnityEngine.Debug:Log(Object) player$$anonymous$$ove:FixedUpdate() (at Assets/Scripts/player$$anonymous$$ove.cs:65)
GameObject found, reference is not null UnityEngine.Debug:Log(Object) player$$anonymous$$ove:FixedUpdate() (at Assets/Scripts/player$$anonymous$$ove.cs:72)
NullReferenceException: Object reference not set to an instance of an object player$$anonymous$$ove.FixedUpdate () (at Assets/Scripts/player$$anonymous$$ove.cs:75)
So what object is null? And when is it beco$$anonymous$$g null? $$anonymous$$eep using debug logs to debug.
Debug.Log("Instantiating harpoon");
Debug.Log("Destroying harpoon");
Debug.Log("firing harpoon");
Debug.Log("Is harpoon null? " + (harpoon == null));
Your answer
Follow this Question
Related Questions
How to make a floppy object 1 Answer
Can't add Orbital script - "The script needs to derive from MonoBehaviour!" 0 Answers
Need help with GameObject placement 2 Answers
How to Parent a Camera to the Head Bone with No Camera Shake? 0 Answers
Null Reference Exception ONLY (sometimes) when loading the scene... 1 Answer