Search Unity

Why am I getting this error?

Discussion in '2D' started by EvMaster114, Mar 4, 2021.

  1. EvMaster114

    EvMaster114

    Joined:
    Dec 11, 2020
    Posts:
    8
    I am trying to my player shoot. I have all the spawning in place but whenever I try to run this code:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Bullet : MonoBehaviour
    6. {
    7.     private Rigidbody2D rb;
    8.     public float bulletSpeed;
    9.     // Update is called once per frame
    10.     void Update()
    11.     {
    12.       rb.velocity = new Vector2(bulletSpeed, rb.velocity.y);
    13.     }
    14. }
    15.  
    I get an error saying : NullReferenceException: Object reference not set to an instance of an object
    Bullet.Update () (at Assets/Bullet.cs:13). Why am I getting this error?
     
  2. Cornysam

    Cornysam

    Joined:
    Feb 8, 2018
    Posts:
    1,463
    Because Rigidbody2D variable is set as private and you haven't set the reference. Hence the NullReference error. Add a Start or Awake method and do:

    rb = GetComponent<Rigidbody2d>();
     
    EvMaster114 likes this.
  3. EvMaster114

    EvMaster114

    Joined:
    Dec 11, 2020
    Posts:
    8
    Thanks!
     
    Cornysam likes this.