Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

[SOLVED] NullReferenceException: Object reference not set to an instance of an object

Discussion in 'Scripting' started by Ljrnet, Jul 29, 2016.

Thread Status:
Not open for further replies.
  1. Ljrnet

    Ljrnet

    Joined:
    Nov 5, 2015
    Posts:
    33
    Hi everyone,

    I am getting an error that I can't wrap my head around:

    "NullReferenceException: Object reference not set to an instance of an object."

    I am using the enemy object as a trigger so that when the player collides with the enemy the player healthbar decreases over time. I have 2 scripts, one for the player healthbar and one for the enemy damage.

    Edit: I am getting the error when the player collides with the enemy.

    Player Healthbar:

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using Image=UnityEngine.UI.Image;
    4.  
    5. public class PlayerHealth : MonoBehaviour
    6. {
    7.     Image Healthbar;
    8.     public float pHealth;
    9.  
    10.     // Use this for initialization
    11.     void Start ()
    12.     {
    13.         Healthbar=GameObject.Find("FPSController").transform.FindChild ("FirstPersonCharacter").transform.FindChild ("Canvas").FindChild ("Healthbar").GetComponent<Image> ();
    14.     }
    15.  
    16.     // Update is called once per frame
    17.     void Update ()
    18.     {
    19.         Healthbar.fillAmount = pHealth;
    20.     }
    21. }
    Enemy Damage:

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class EnemyDamage : MonoBehaviour
    5. {
    6.     public PlayerHealth pHealth;
    7.  
    8.     // Use this for initialization
    9.     void Start ()
    10.     {
    11.         pHealth = GetComponent<PlayerHealth>();
    12.     }
    13.  
    14.     // Update is called once per frame
    15.     void Update ()
    16.     {
    17.  
    18.     }
    19.  
    20.     void OnTriggerStay(Collider other)
    21.     {
    22.         if (other.CompareTag("Player"))
    23.         {
    24.             GetComponent<PlayerHealth>().pHealth -= 0.1f;
    25.         }
    26.     }
    27. }
    Any help appreciated. Thanks.
     
    Last edited: Jul 29, 2016
  2. jister

    jister

    Joined:
    Oct 9, 2009
    Posts:
    1,749
    Didn't read on beyond this
    using Image=UnityEngine.UI.Image;
    Where did you get this and what does it suppose to do or mean???

    Edit: ok wauw I read on a bit...
    Healthbar=GameObject.Find("FPSController").transform.FindChild ("FirstPersonCharacter").transform.FindChild ("Canvas").FindChild ("Healthbar").GetComponent<Image> ();

    You should learn how to use the docs.
    https://docs.unity3d.com/ScriptReference/Transform.Find.html
     
  3. Ljrnet

    Ljrnet

    Joined:
    Nov 5, 2015
    Posts:
    33
    This is the full error message:

    NullReferenceException: Object reference not set to an instance of an object
    EnemyDamage.OnTriggerStay (UnityEngine.Collider other) (at Assets/Scripts/EnemyDamage.cs:24)
    .
    and when I double click on it sends me to the EnemyDamage script on line 24.
     
  4. LiterallyJeff

    LiterallyJeff

    Joined:
    Jan 21, 2015
    Posts:
    2,807
    That means that GetComponent<PlayerHealth>() is returning null. Do you mean to do other.gameObject.GetComponent<PlayerHealth>()?

    Also in your PlayerHealth class, change "Image Healthbar" to "public Image Healthbar", and drag and drop that Image object in the inspector. Don't bother with the crazy "Find" function chain on Start.
     
    dannyzapata619 and Ljrnet like this.
  5. Ljrnet

    Ljrnet

    Joined:
    Nov 5, 2015
    Posts:
    33
    Thank you so much it works now.
     
    Diskomuz and LiterallyJeff like this.
  6. unknownsk

    unknownsk

    Joined:
    Jan 16, 2020
    Posts:
    36
    Hey bro pls solve my error too pls reply me and i will send you information
     
  7. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,773
    That's not how this works, that's not how any of this works.

    Make a post. Describe your problem. If you post code, use code tags. Then, you may get some replies.
     
  8. huseyinbaba58

    huseyinbaba58

    Joined:
    Feb 12, 2020
    Posts:
    146
    I want to more details about this topic.
     
  9. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,773
    That's not how this works, that's not how any of this works.

    Make a post. Describe your problem. If you post code, use code tags.

    (Yes, I just copied and pasted my last comment on the thread, but apparently it needed repeating)
     
  10. ShokWayve

    ShokWayve

    Joined:
    Jan 16, 2013
    Posts:
    136
    LOL!

    Funny and helpful.
     
    Moritzunity9 likes this.
  11. TheRealLittleBoi

    TheRealLittleBoi

    Joined:
    Feb 18, 2021
    Posts:
    3
    I have the same problem but with my sound manager, Im trying to add a Sound Effect when the character jumps and preforms other actions but I get the same error message.
    Here are both my my scripts for my player controller and my sound manager.

    Player Controller


    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. public class PlayerController : MonoBehaviour
    4. {
    5.     public float speed = 5f;
    6.     public float jumpspeed = 5f;
    7.     private float movement = 0f;
    8.     private Rigidbody2D rigidBody;
    9.     public Transform groundCheckPoint;
    10.     public float groundCheckRadius;
    11.     public LayerMask groundLayer;
    12.     private bool isTouchingGround;
    13.     private Animator playerAnimation;
    14.     public Vector3 respawnPoint;
    15.     public LevelManager gameLevelManager;
    16.  
    17.  
    18.     // Use this for initialization
    19.     void Start()
    20.     {
    21.         rigidBody = GetComponent<Rigidbody2D>();
    22.         playerAnimation = GetComponent<Animator>();
    23.         respawnPoint = transform.position;
    24.         gameLevelManager = FindObjectOfType<LevelManager> ();
    25.     }
    26.  
    27.     // Update is called once per frame
    28.     void Update()
    29.     {
    30.         isTouchingGround = Physics2D.OverlapCircle(groundCheckPoint.position, groundCheckRadius, groundLayer);
    31.         movement = Input.GetAxis("Horizontal");
    32.         if (movement > 0f)
    33.         {
    34.             rigidBody.velocity = new Vector2(movement * speed, rigidBody.velocity.y);
    35.             transform.localScale = new Vector2(1, 1);
    36.         }
    37.         else if (movement < 0f)
    38.         {
    39.             rigidBody.velocity = new Vector2(movement * speed, rigidBody.velocity.y);
    40.             transform.localScale = new Vector2(-1, 1f);
    41.         }
    42.         else
    43.         {
    44.             rigidBody.velocity = new Vector2(0, rigidBody.velocity.y);
    45.         }
    46.         if (Input.GetButtonDown("Jump") && isTouchingGround)
    47.         {
    48.             rigidBody.velocity = new Vector2(rigidBody.velocity.x, jumpspeed);
    49.             SoundManagerScript.PlaySound("JumpSoundEffect");
    50.         }
    51.  
    52.         playerAnimation.SetFloat("Speed", rigidBody.velocity.x);
    53.         playerAnimation.SetBool("OnGround", isTouchingGround);
    54.     }
    55.  
    56.     void OnTriggerEnter2D(Collider2D other)
    57.     {
    58.         if (other.tag == "FallDetector") {
    59.             gameLevelManager.Respawn();
    60.         }
    61.         if (other.tag == "Checkpoint") {
    62.             respawnPoint = other.transform.position;
    63.         }
    64.     }
    65.   }


    Sound Manager


    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class SoundManagerScript : MonoBehaviour
    6. {
    7.  
    8.     public static AudioClip playerHitSound, jumpsound, coinSound;
    9.     static AudioSource audioSrc;
    10.  
    11.  
    12.  
    13.     // Start is called before the first frame update
    14.  
    15.     void Start()
    16.     {
    17.         playerHitSound = Resources.Load<AudioClip>("HitSoundEffect");
    18.         jumpsound = Resources.Load<AudioClip>("JumpSoundEffect");
    19.         coinSound = Resources.Load<AudioClip>("Coin");
    20.  
    21.         audioSrc = GetComponent<AudioSource>();
    22.     }
    23.  
    24.  
    25.  
    26.  
    27.     // Update is called once per frame
    28.     void Update()
    29.     {
    30.  
    31.     }
    32.  
    33.     public static void PlaySound(string clip)
    34.     {
    35.  
    36.         switch (clip)
    37.         {
    38.             case "HitSoundEffect":
    39.                 audioSrc.PlayOneShot(playerHitSound);
    40.                 break;
    41.             case "JumpSoundEffect":
    42.                 audioSrc.PlayOneShot(jumpsound);
    43.                 break;
    44.             case "Coin":
    45.                 audioSrc.PlayOneShot(coinSound);
    46.                 break;
    47.         }
    48.     }
    49. }
    Please help me
     
  12. mopthrow

    mopthrow

    Joined:
    May 8, 2020
    Posts:
    348
    It's good that you used code tags, but please make your own thread and copy/paste the full error message. Makes it much easier to help ;)
     
  13. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,519
    PLEASE ... Stop posting to five-year-old threads... it is against forum rules.

    Instead, post your own new thread.

    Null Reference is the silliest simplest most trivial error EVER... and therefore the answer is always the same... ALWAYS. It is the single most common error ever.

    Don't waste your life spinning around and round on this error. Instead, learn how to fix it fast... it's EASY!!

    Some notes on how to fix a NullReferenceException error in Unity3D
    - also known as: Unassigned Reference Exception
    - also known as: Missing Reference Exception
    - also known as: Object reference not set to an instance of an object

    http://plbm.com/?p=221

    The basic steps outlined above are:
    - Identify what is null
    - Identify why it is null
    - Fix that.

    Expect to see this error a LOT. It's easily the most common thing to do when working. Learn how to fix it rapidly. It's easy. See the above link for more tips.

    This is the kind of mindset and thinking process you need to bring to this problem:

    https://forum.unity.com/threads/why-do-my-music-ignore-the-sliders.993849/#post-6453695

    Step by step, break it down, find the problem.
     
    K1327399 and sjameselvis like this.
  14. mushroomseasonisopen666420

    mushroomseasonisopen666420

    Joined:
    Apr 23, 2020
    Posts:
    16

    Maybe that's why it's posted about so often, considering that Unity is also the premier engine for all kinds of beginners to learn game design.

    I'm looking up this thread because an asset I paid for is giving this error, among others. I'm not even a programmer, I'm an artist.
     
  15. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,519
    This could be the asset, this could be the use of it. Check the support links for that asset.

    Either way, whatever it is, it is unhelpful to the forum to respond to five-year-old threads with completely unrelated posts.

    Please start your own fresh thread. That's what the forum rules actually say to do:

    https://forum.unity.com/threads/unity-community-code-of-conduct.743180/

    I quote:

    1i. Pointless necroposting (posting in a forum thread that is too old to matter any more, or has served its purpose)

    Start new threads in appropriate forums – Look at the sections and their descriptions before you post.
     
    K1327399 and gaglabs like this.
  16. gaglabs

    gaglabs

    Joined:
    Oct 17, 2019
    Posts:
    185
    WOW, we waking the dead now :p
     
    K1327399 and Kurt-Dekker like this.
  17. Zouxayt

    Zouxayt

    Joined:
    Nov 28, 2021
    Posts:
    2
    hoe to fix

    upload_2021-12-3_15-28-57.png
     
  18. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,321
    Hoe? Please at least read the threads you're raising from the dead before posting.

    I'm going to lock this thread as it's just a magnet for NullReferenceException posts of which there are dozens each day.

    Thanks.
     
    K1327399, twitchyvr and Kurt-Dekker like this.
Thread Status:
Not open for further replies.