NullReferenceExeption

I get the error “NullReferenceExeption” in line 17 in this code, but i cant find it! Help?

using UnityEngine;
using System.Collections;

public class shoot : MonoBehaviour {
    public GameObject bullet_prefab;
    public float bulletImpulse = 100f;
    // Use this for initialization
    void Start () {
  
    }
  
    // Update is called once per frame
    void Update () {
  
        if (Input.GetButtonDown ("Fire1")) {
            Camera cam = Camera.current;
            GameObject thebullet = (GameObject)Instantiate (bullet_prefab, cam.transform.position + cam.transform.forward, cam.transform.rotation);
            thebullet.GetComponent<Rigidbody>().AddForce(cam.transform.forward * bulletImpulse, ForceMode.Impulse);
        }
    }
}

edit: sorry for no code tags…

1 Like

[code ][/code ] tags please.

Also, use Camera.main and not Camera.current. Do you actually have a prefab assigned to the bullet_prefab in the inspector? And does the GameObject in the prefab actually have a Rigidbody assigned to it?

1 Like

can you edit it as code

[code ]

[/code ]

1 Like
public GameObject bullet_prefab;
thebullet.GetComponent<Rigidbody>()

Are meant to be the same prefab?

And please use code tags as asked next time.

Camera.current is needed, because its part of a multiplayer game, and i would be shooting multiple projectiles otherwise, and yes I have essigned a prefab…

no, they are not

so in which line is your null reference exception now, looking at your code line 17 is empty

public class shoot : MonoBehaviour
{
   public GameObject bullet_prefab;
   public float bulletImpulse = 100f;

   void Update ()
   {
       if(Input.GetButtonDown ("Fire1"))
       {
           if(bullet_prefab == null)
              Debug.Log("null prefab");

           Camera cam = Camera.current;

           if(cam == null)
              Debug.Log("null camera");
           
           GameObject theBullet = GameObject.Instantiate(bullet_prefab, cam.transform.position + cam.transform.forward, cam.transform.rotation);

            if(theBullet == null)
               Debug.Log("null bullet");

            Rigidbody bulletRigidbody = theBullet.GetComponent<Rigidbody>();

            if(bulletRigidbody == null)
               Debug.Log("null rigidbody");

            bulletRigidbody.AddForce(cam.transform.forward * bulletImpulse, ForceMode.Impulse);
       }
   }
}

Welcome to the world of debugging.

1 Like

Ahh… I’ll just say, a null reference exception basically means that you’re trying to push a button on a device that doesn’t exist. Make sure when you tell a computer to press a button that the button exists, or they get very angry.