• 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
Question by Remulos1 · Mar 13, 2017 at 08:20 PM · error messagenull reference exception

is my enemy selector null reference a problem?

Hello Everyone,

I'm new to Unity but I'm getting along so far from the great tutorials and questions that have already been answered. I have created the script below to display the health of enemy or companion characters but which character is dependent on a Raycast from the camera (in the direction of the player) and is not initialised in void Start(). I get the "NullReferenceException" error from line 40 but it is still playable and works as intended. I just think there must be a way to code this better to avoid the error.

     CharacterHealthManager playerHealth;
     CharacterHealthManager selectedHealth;
     CanvasGroup cg;
 
     public Slider healthBar;
     public Slider selectedHealthBar;
     public Image selectedHealthBarFill;
     public Text hpText;
     public Text selectedHPText;
     public Text objName;
 
     // Use this for initialization
     void Start () {
 
         playerHealth = GameObject.FindGameObjectWithTag("Player").GetComponent<CharacterHealthManager>();
         cg = GetComponentInChildren<CanvasGroup>();
 
     }
 
     // Update is called once per frame
     void Update() {
         
         healthBar.maxValue = playerHealth.characterMaxHealth;
         healthBar.value = playerHealth.characterCurrentHealth;
         hpText.text = "HP: " + playerHealth.characterCurrentHealth + "/" + playerHealth.characterMaxHealth;
 
         DisplaySelectedHealth();
     }
 
     void DisplaySelectedHealth()
     {
 
         if (GameObject.FindGameObjectWithTag("MainCamera").GetComponent<MouseManager>().selectedObject.GetComponent<CharacterHealthManager>() != null)
         {
             cg.alpha = 1;
             selectedHealth = GameObject.FindGameObjectWithTag("MainCamera").GetComponent<MouseManager>().selectedObject.GetComponent<CharacterHealthManager>();
 
             if (selectedHealth.CompareTag("Ally"))
             {
                 selectedHealthBarFill.color = Color.magenta;
                 //TODO add Color.Lerp for smooth color transition.
             }
             else if (selectedHealth.CompareTag("Enemy"))
             {
                 selectedHealthBarFill.color = Color.black;
             }
 
             objName.text = ("" + selectedHealth.name);
             selectedHealthBar.maxValue = selectedHealth.characterMaxHealth;
             selectedHealthBar.value = selectedHealth.characterCurrentHealth;
             selectedHPText.text = "HP: " + selectedHealth.characterCurrentHealth + "/" + selectedHealth.characterMaxHealth;
         }
         else
         {
             cg.alpha = 0;
         }
 
     }
 }

Comment

People who like this

0 Show 1
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 Commoble · Mar 14, 2017 at 02:00 AM 0
Share

Firstly, if you don't post your script starting from the very first line, we can't tell which line Line 40 is unless you point it out to us with an inline comment.

Secondly, Unity is pretty robust and won't crash from most runtime errors, but having an error like this still means that things won't work the way you intend them to if you don't fix it.

Thirdly, a null reference error means you're trying to reference a member of an instance that doesn't exist, i.e. you're accessing someVariable.someFunctionOrVariable when someVariable is null.

Find Line 40, figure out what's null in that line that's not supposed to be null, figure out WHY it's null when it's not supposed to be null, and then you'll be able to fix your error.

EDIT: Fourthly, this is unrelated, but it's generally Not Good to find an object by string in every Update, and Doubly Not Good to search for the same object several times in the same Update step. Best practice for when you have to search for an object by name or tag is to do it once (typically in the Start event) and save a reference to that object in a variable.

1 Reply

· Add your reply
  • Sort: 
avatar image
Best Answer

Answer by Socapex · Mar 15, 2017 at 05:12 AM

 if (thing != null) {
     DoSomething();
 }
 

;)

Ok, if it isn't ever supposed to be null, you can use asserts. This will at least warn you during development time.

 using UnityEngine.Assertions;
 
 Assert.IsNotNull(thingy);

Finally, yes it matters. Exceptions will rewind your stack and leave you in undefined state. If it continues working, that is pure luck. You need to fix it, most often you can just make sure it isn't null.

Comment

People who like this

0 Show 0 · 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

96 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

Related Questions

GameObject only spawning 60% of the time (c#) 1 Answer

ArgumentNullException: Value cannot be null. parameter name: Source 1 Answer

Are there any cases in that unity ignores the exception and runs the next code? 1 Answer

Object reference not set to an instance of an object ERROR - Idk why 1 Answer

Null Reference Exception Error 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