Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

NullReferenceException

Discussion in 'Scripting' started by NintendoMaster00, Feb 29, 2016.

  1. NintendoMaster00

    NintendoMaster00

    Joined:
    Jan 31, 2015
    Posts:
    86
    I am getting this error:
    NullReferenceException: Object reference not set to an instance of an object
    Script_Name.Update () (at Assets/Scripts/Script_Name.cs:37)
    here is the part of my code that is causing the problem
    Code (CSharp):
    1. RaycastHit2D hit = Physics2D.Raycast(position, playermovement.Direction * RayLength);
    2.             {
    3.                 string collidername = hit.collider.name;
    4.                 switch(collidername)
    5.                 {
    6.                //switch statment stuff in here
    7.                 }
    8.  
    this is the specific line that is causing the error
    Code (CSharp):
    1. string collidername = hit.collider.name;
     
  2. DanielQuick

    DanielQuick

    Joined:
    Dec 31, 2010
    Posts:
    3,137
    The code is called whether or not anything is hit, so you have to check first.

    Code (csharp):
    1. if(hit.collider != null) {
    2.     string collidername =hit.collider.name;
    3.  
    4.     ...
    5. }
     
    NintendoMaster00 and LeftyRighty like this.
  3. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    you're mixing up the 3d raycasthit and the 2d raycasthit syntax...

    in 3d it's
    Code (csharp):
    1.  
    2. //pseudo
    3. if(raycast, out hit)
    4. { ... we hit something... }
    5.  
    in the 2d its
    Code (csharp):
    1.  
    2. //pseudo
    3. hit = raycast
    4. if(hit)
    5. { ... we hit something... }
    6.  
     
    NintendoMaster00 likes this.
  4. NintendoMaster00

    NintendoMaster00

    Joined:
    Jan 31, 2015
    Posts:
    86