• 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 /
avatar image
0
Question by MoeRobinson · Jan 17, 2017 at 08:11 AM · nullreferenceexception

Object reference not set to an instance of an object? Looked everywhere for help.

I am here to Learn how to better debug c# scripts better any feed back is appreciated. Here is the code in question:

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class BoxDMG : MonoBehaviour {
     float damage = 5f;
     // Use this for initialization
     void Start () {
         
     }
     
     // Update is called once per frame
     void Update () {
         
     }
     void OnTriggerEnter2D (Collider2D other)
     {
         if (other == null)
         {
             Debug.Log("other is null so fix it");
         }
 
         other.gameObject.GetComponent<HealthBar>().TakeDamage(damage);
 
         if (other.gameObject == null)
         {
             Debug.Log ("other.gameObject is null so fix it");
         }
 
     }
 }

as you can see i have been trying to test everything and see what it is that is coming out as null this script is put on a sprite that also as a Box Collider. the Health bar its referring to is here:

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using UnityEngine.UI;
 
     public class HealthBar : MonoBehaviour {
     public float curHealth = 4f;
     public float maxHealth = 10f;
     public bool playerDead = false;
     public Image Bar;
     
     // Use this for initialization
     void Start () {
         SetHealth();
     }
 
     // Update is called once per frame
     public void TakeDamage (float amount) {
         curHealth -= amount;
         SetHealth ();
     }
     public void SetHealth (){
         float healthPercent = curHealth / maxHealth;
         Bar.fillAmount = healthPercent;
     }
 
 }

this script is attached to a UI element to display my health. it seems to work fine on its own. as when i set the health manually it decreased my health bar in the UI accordingly.

Whenever my player model touches the box that has the first script attached to it, the game pauses and i get this error:

NullReferenceException: Object reference not set to an instance of an object BoxDMG.OnTriggerEnter2D (UnityEngine.Collider2D other) (at Assets/Scripts/BoxDMG.cs:19)

Since line 19 is where "other" is stated, i figured that it was trying to tell me that the variable "other" was returning a null value or wasant attached to an object. but after testing using "return" commands and "DeBug.Log" commands to test, neither of those were true.

Please Help, thanks.

Comment
Add comment · Show 4
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 doublemax · Jan 17, 2017 at 08:14 AM 2
Share
 other.gameObject.GetComponent<HealthBar>().TakeDamage(damage);

$$anonymous$$ost likely GetComponent() returns null and then you're trying to call a method with it => exception.

And the other.gameObject check for null should be before that.

avatar image MoeRobinson doublemax · Jan 17, 2017 at 04:02 PM 0
Share

I've changed where the null check is in the code and it didn't return anything in the console, so as you said it probably has to do with the component I'm getting. This being said Visual Studio knows what class I'm trying to call when i type Hea... it auto corrects it in the drop down menu and when i call the method from that class it also know what I'm referring too. thanks for the feedback but i still need to find out how to fix it. thanks.

avatar image Glurth MoeRobinson · Jan 17, 2017 at 05:32 PM 2
Share

If the object that is colliding with the BoxD$$anonymous$$G, does NOT have a HealthBar component, then other.gameObject.GetComponent<HealthBar>() SHOULD return null.

I'm not sure how your scene is setup, but perhaps some object you don't expect to be colliding, actually is.

Show more comments

1 Reply

· Add your reply
  • Sort: 
avatar image
0
Best Answer

Answer by MoeRobinson · Jan 18, 2017 at 08:22 AM

FIXED! thanks to Glurth and doublemax. HealthBar was attached to a ui element and not the player that was iteracting with the box to take damage. Here are the updated scripts:

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using UnityEngine.UI;
 using UnityEngine.SceneManagement;
 
 public class HealthBar : MonoBehaviour
 {
     public float curHealth = 10f;
     public float maxHealth = 10f;
     public Image Bar;
    
 
     // Use this for initialization
     void Start()
     {
      
         SetHealth();
     }
 
     // Update is called once per frame
     public void TakeDamage(float amount)
     {
         curHealth -= amount;
         SetHealth();
     }
     public void SetHealth()
     {
         float healthPercent = curHealth / maxHealth;
         Bar.fillAmount = healthPercent;
 
         if (curHealth <= 0)
         {
             Death();
         }
 
 
     }
     public void Death()
     {
         SceneManager.LoadScene("DeathMenu");
     }
    
 }
 

This is attached to the player then you drag and drop the healthbar sprite onto the "Bar" image variable i the inspector. here is the other script:

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class BoxDMG : MonoBehaviour {
     float damage = 1f;
     
     void OnTriggerEnter2D (Collider2D other)
     {
         other.gameObject.GetComponent<HealthBar>().TakeDamage(damage);
     }
 }
 


Thanks for the help. PEACE.

Comment
Add comment · 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

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.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

6 People are following this question.

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

Related Questions

NullReferenceException 2 Answers

Material[] Object reference not set when instantiating 2 Answers

NullReference Exception when adding a class 2 Answers

NullReferenceException 1 Answer

Raycasthit NullRException 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