Search Unity

‘Object reference not set to an instance of an object’

Discussion in 'Scripting' started by HarryIsBeast, Aug 29, 2015.

  1. HarryIsBeast

    HarryIsBeast

    Joined:
    Aug 25, 2015
    Posts:
    19
    I keep getting the error in my console that says 'Object reference not set to an instance of an object' I know what this error means but I'm not sure how to fix it in my case. If anyone could help that would be great, here is the code. (The error is on line 12 'healthBar.fillAmount = .0f;' if you can provide what needs to be defined and how to define it that would be great)
    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.UI;
    3. using System.Collections;
    4.  
    5.  
    6. public class CollisionJawn : MonoBehaviour {
    7.     void OnCollisionEnter (Collision col)
    8.     {
    9.         if(col.gameObject.name == "AircraftJet")
    10.         {
    11.             Image healthBar = GetComponent<Image>();
    12.             healthBar.fillAmount = .0f;
    13.         }
    14.     }
    15. }
     
  2. Lorinthio

    Lorinthio

    Joined:
    Aug 7, 2015
    Posts:
    39
    Does the object this script is on, actually have an Image component? If it doesn't that would make healthBar practically null, and would throw that error. (As far as I'm aware!)
     
  3. HarryIsBeast

    HarryIsBeast

    Joined:
    Aug 25, 2015
    Posts:
    19
    @Lorinthio Yes, there is an image in the canvas named healthBar
     
  4. EETechnology

    EETechnology

    Joined:
    Aug 15, 2015
    Posts:
    185
    Im not very sure but try to get the component in start function. So dont do GetComponent there but in start, then you can leave the other part as it is. :)
     
  5. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    Null reference means "something before a dot is null". In this case healthBar.

    It's possibly because this script is on a different component from the Image component. Or healthBar could be being destroyed.