Why am I getting this error?

I am trying to my player shoot. I have all the spawning in place but whenever I try to run this code:

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

public class Bullet : MonoBehaviour
{
    private Rigidbody2D rb;
    public float bulletSpeed;
    // Update is called once per frame
    void Update()
    {
      rb.velocity = new Vector2(bulletSpeed, rb.velocity.y);
    }
}

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?

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();

1 Like

Thanks!

1 Like