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

NullReferenceException Error: Raycast Ground Check Problem

Discussion in 'Scripting' started by S-Blaze, Jan 4, 2019.

  1. S-Blaze

    S-Blaze

    Joined:
    Nov 22, 2018
    Posts:
    3
    Hey guys!
    I'm creating a 2D platformer game and I'm running into a NullReferenceException error.

    You can look at my code below(The "!!!!" indicate the places which, I think, are related to the error):
    Code (CSharp):
    1. public class Player : MonoBehaviour {
    2.  
    3.     //movement variables
    4.     [SerializeField] float speed;
    5.  
    6.     private bool isFacingRight;
    7.  
    8.     //jump variables !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    9.     [SerializeField] float jumpForce;
    10.  
    11.     bool isGrounded;
    12.     float groundCheckRadius = 0.1f;
    13.     [SerializeField] LayerMask groundLayer;
    14.     [SerializeField] Transform groundCheck;
    15.  
    16.     //attack anim variables
    17.     bool isAttacking;
    18.     public GameObject attackLeaf1;
    19.     public GameObject attackLeaf1inv;
    20.     [SerializeField] float attack1Delay;
    21.     //attack variables
    22.     float hitCheckRadius = 0.3f;
    23.     [SerializeField] LayerMask hitLayer;
    24.     [SerializeField] Transform hitCheck;
    25.  
    26.     //general variables
    27.     Rigidbody2D rb;
    28.     Animator anim;
    29.  
    30.     private void Start () {
    31.         rb = GetComponent<Rigidbody2D>();
    32.         anim = GetComponent<Animator>();
    33.  
    34.         isFacingRight = true;
    35.     }
    36.    
    37.     private void Update(){
    38.         if(!isAttacking){
    39.             verticalMovement();
    40.             horizontalMovement();
    41.             checkGround(); //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    42.  
    43.             if(Input.GetKeyDown(KeyCode.J) && isGrounded == true){
    44.                 attack();
    45.             }
    46.         }
    47.     }
    48.  
    49.     void attack(){
    50.         isAttacking = true;
    51.         anim.SetBool("isAttacking", isAttacking);
    52.  
    53.         Vector3 scale = transform.localScale;
    54.         var attackLeaf1Scale = attackLeaf1.transform.localScale.x;
    55.  
    56.         if(scale.x == 1f){
    57.             Instantiate(attackLeaf1, transform.position + new Vector3(0.545f, -0.024f, 0), Quaternion.identity);
    58.         }if(scale.x == -1f){
    59.             Instantiate(attackLeaf1inv, transform.position + new Vector3(-0.545f, -0.024f, 0), Quaternion.identity);
    60.         }
    61.  
    62.  
    63.         StartCoroutine(stopAnim(attack1Delay));
    64.     }
    65.  
    66.     IEnumerator stopAnim(float delay){
    67.         yield return new WaitForSeconds(delay);
    68.  
    69.         isAttacking = false;
    70.         anim.SetBool("isAttacking", isAttacking);
    71.     }
    72.  
    73.     void horizontalMovement(){
    74.         float horizontalInput = Input.GetAxis("Horizontal");
    75.  
    76.         transform.Translate(Vector2.right * horizontalInput * speed * Time.deltaTime);
    77.  
    78.         if (horizontalInput > 0 && !isFacingRight)
    79.         {
    80.             flip();
    81.         }
    82.         else if (horizontalInput < 0 && isFacingRight)
    83.         {
    84.             flip();
    85.         }
    86.  
    87.         anim.SetFloat("speed", Mathf.Abs(horizontalInput));
    88.     }
    89.  
    90.     //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    91.     void checkGround(){
    92.  
    93.         RaycastHit2D hit = Physics2D.Raycast(groundCheck.position, -Vector3.up, 0.1f);
    94.  
    95.         if(hit.collider.gameObject.layer == LayerMask.NameToLayer("Ground")){  //IT SAYS THE PROBLEM IS HERE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    96.             isGrounded = true;
    97.  
    98.             anim.SetBool("isGrounded", isGrounded);
    99.  
    100.             anim.SetFloat("verticalSpeed", rb.velocity.y);
    101.         }
    102.  
    103.         Vector3 endLine = groundCheck.position - new Vector3(0, -0.1f, 0);
    104.  
    105.         Debug.DrawLine(groundCheck.position, endLine, Color.green, 1, true);
    106.     }
    107.  
    108.     void verticalMovement(){
    109.         float verticalInput = Input.GetAxis("Jump");
    110.  
    111.         if(isGrounded && verticalInput>0){
    112.             isGrounded = false;
    113.             anim.SetBool("isGrounded", isGrounded);
    114.  
    115.             transform.Translate(Vector2.up * verticalInput * jumpForce * Time.deltaTime);
    116.             rb.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
    117.         }
    118.     }
    119.  
    120.     void flip(){
    121.         isFacingRight = !isFacingRight;
    122.         Vector3 scale = transform.localScale;//setting "scale" equal to the current scale of the object.
    123.  
    124.         scale.x *= -1f;
    125.  
    126.         transform.localScale = scale;
    127.     }
    128. }
    129.  
    Here are the things I've defined in the inspector.
    Screen Shot 2019-01-02 at 10.51.24 PM.png

    The error isn't really affecting the game but when my character jumps, the following error comes up during the time the character's in the air:
    Screen Shot 2019-01-02 at 10.50.54 PM.png

    Help would be greatly appreciated! Thank you!
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,971
    Did you look at the reference docs for the function here:

    https://docs.unity3d.com/ScriptReference/Physics2D.Raycast.html

    Specifically, and I quote:

    "This function returns a RaycastHit2D object with a reference to the collider that is hit by the ray (the collider property of the result will be NULL if nothing was hit)."

    Is that what is happening?
     
    WallaceT_MFM likes this.
  3. SparrowGS

    SparrowGS

    Joined:
    Apr 6, 2017
    Posts:
    2,536
    Next time please also put your "using" tags in there too, i looked at the error and went to look at line 100,
    Code (CSharp):
    1. anim.SetFloat("verticalSpeed", rb.velocity.y);
    2.  

    in your "if" check to see that "hit" isn't null before testing for "hit.whatever".

    *So happy the 3D version returns a bool right now, haha.
     
  4. WallaceT_MFM

    WallaceT_MFM

    Joined:
    Sep 25, 2017
    Posts:
    394
    This is likely the problem, given how short the raycasts are set to be. You need to null check the RaycastHit2D's collider before accessing it.
    if(hit.collider != null && hit.collider.gameObject.layer == LayerMask.NameToLayer("Ground"))
     
  5. S-Blaze

    S-Blaze

    Joined:
    Nov 22, 2018
    Posts:
    3
    Thank you guys for responding.
    I tested it and, yes, that was the problem. I needed to add the "hit.collider != null" parameter to the ground check.
    @WallaceT_MFM Sorry about not adding the full script, I haven't really used the unity forums much and it didn't occur to me to do so.