Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
  • Help Room /
avatar image
0
Question by George-B · Jul 05, 2016 at 12:30 AM · c#gameobjecterror messagephysics2dprojectile

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
   
 }
 
 }









Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
1

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.

Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image George-B · Jul 05, 2016 at 06:27 PM 0
Share

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)

avatar image Jessespike George-B · Jul 05, 2016 at 09:41 PM 0
Share

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

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

181 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

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


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges