0

i'm programming in C# with unity version 2018.4.32F1, and i made a prototype where the player can jump, and i used the Boxcast (Raycast) function to know when the player touch the ground or not.

In-game, it work perfectly fine, but the console still write :

NullReferenceException: Object reference not set to an instance of an object PlayerControl.Update () (at Assets/scripts/Player/PlayerControl.cs:54)

So here is the program :

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class test : MonoBehaviour
{
    private bool grounded = false;

    private float jumpForce = 7;
    private float JumpCooldown = 0.4f;
    private float JumpTimeStamp;

    private Rigidbody2D PlayerRigidbody;
    private BoxCollider2D boxcollider2D;


    // Start is called before the first frame update
    void Start()
    {
        PlayerRigidbody = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        //jumping
        if (Input.GetKeyDown(KeyCode.UpArrow) && grounded == true)
        {
            JumpTimeStamp = Time.time + JumpCooldown;
            grounded = false;
            PlayerRigidbody.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
        }

        //collision with the down side of the player
        RaycastHit2D raycastHit2D = Physics2D.BoxCast(boxcollider2D.bounds.center, boxcollider2D.size, 0f, Vector2.down, 0.1f);

        if (raycastHit2D.collider.gameObject.name == "Ground tilemap" && JumpTimeStamp <= Time.time)
        {
            grounded = true;
        }

    }
}

I don't know where it fails, and before i add the "&& JumpTimeStamp <= Time.time" at the end of the line 54, it worked perfectly fine !

derHugo
  • 68,790
  • 9
  • 58
  • 97
fireslide
  • 13
  • 4
  • The error comes Most probably rather from the first part `raycastHit2D.collider.gameObject.name` .. what if your `BoxCast` doesn't hit anything? Also I think an [`OverlapBox`](https://docs.unity3d.com/ScriptReference/Physics2D.OverlapBox.html) would be better for your usecase! – derHugo Jul 24 '21 at 18:08

0 Answers0