0

My player doesn't die and the error that the console gives me is:

NullReferenceException: Object reference not set to an instance of an object Movement.OnCollisionEnter2D (UnityEngine.Collision2D collision) (at Assets/Scripts/Movement.cs:74.

My ground has already the tag ground but the game still gives me this. The ground has the collider too + rigidbody2d

public class Movement : MonoBehaviour
{
    public float moveSpeed = 300;
    public GameObject character;
    private Rigidbody2D characterBody;
    private float ScreenWidth;
    private Rigidbody2D rb2d;
    private Score gm;
    public bool isDead = false;
    public Vector2 jumpHeight;

    void Start()
    {
        ScreenWidth = Screen.width;
        characterBody = character.GetComponent<Rigidbody2D>();
        gm = GameObject.FindGameObjectWithTag("gameMaster").GetComponent<Score>();
    }

    // Update is called once per frame
    void Update()
    {
        if (isDead) { return; }
        if (Input.GetMouseButtonDown(0) || Input.GetKeyDown(KeyCode.Space))  //makes player jump
        {
            GetComponent<Rigidbody2D>().AddForce(jumpHeight, ForceMode2D.Impulse);
        }
        int i = 0;
        while (i < Input.touchCount)
        {
            if (Input.GetTouch(i).position.x > ScreenWidth / 2)
            {
                RunCharacter(1.0f);

            }
            if (Input.GetTouch(i).position.x < ScreenWidth / 2)
            {
                RunCharacter(-1.0f);
            }
            ++i;
        }
    }

    void FixedUpdate()
    {
#if UNITY_EDITOR
        RunCharacter(Input.GetAxis("Horizontal"));
#endif 

    }

    private void RunCharacter(float horizontalInput)
    {
        characterBody.AddForce(new Vector2(horizontalInput * moveSpeed * Time.deltaTime, 0));

    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.CompareTag("ground")) // this will return true if the collision gameobject has ground tag on it.
        {
            isDead = true;
            rb2d.velocity = Vector2.zero;
            GameController.Instance.Die();
        }
    }

    void OnTriggerEnter2D(Collider2D col)
    {
        if (col.CompareTag("coin"))
        {
            Destroy(col.gameObject);
            gm.score += 1;
        }
    }
}
derHugo
  • 83,094
  • 9
  • 75
  • 115
  • and the tag is "ground" not "Ground"? which exactly line is line 74?? not that you seem to have set rb2d to anything.. – BugFinder May 02 '19 at 21:47

1 Answers1

0

As BugFinder said, you never said which line is line 74. One thing I can see is that you never set a value for rb2d. In your Start() method, you can add:

rb2d = GetComponent<Rigidbody2D>();

This should fix that issue. If there are any others, please comment and say what line 74 is. :)