Chapter 7 page 183 (NullReferenceException: Object reference not set to an instance of an object Gun.fireBullet () (at Assets/Scripts/Gun.cs:17))

I have just finished page 182 in the book

I am trying to test the game and I am getting an error in Unity

it runs until I shoot then it stops and produces the following error

NullReferenceException: Object reference not set to an instance of an object
Gun.fireBullet () (at Assets/Scripts/Gun.cs:17)

I have checked my code against the code that I downloaded to accompany the book and it’s the same.

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

public class Gun : MonoBehaviour {

public GameObject bulletPrefab;
public Transform launchPosition;
public bool isUpgraded;
public float upgradeTime = 10.0f;

private float currentTime;
private AudioSource audioSource;

void fireBullet() {
Rigidbody bullet = createBullet();
bullet.velocity = transform.parent.forward * 100;
if (isUpgraded) {
Rigidbody bullet2 = createBullet();
bullet2.velocity = (transform.right + transform.forward / 0.5f) * 100;
Rigidbody bullet3 = createBullet();
bullet3.velocity = ((transform.right * -1) + transform.forward / 0.5f) * 100;
}
if (isUpgraded) {
audioSource.PlayOneShot(SoundManager.Instance.upgradedGunFire);
} else {
audioSource.PlayOneShot(SoundManager.Instance.gunFire);
}
}

public void UpgradeGun() {
isUpgraded = true;
currentTime = 0;
}

// Use this for initialization
void Start () {
audioSource = GetComponent();
}

// Update is called once per frame
void Update () {
if (Input.GetMouseButtonDown(0)) {
  if (!IsInvoking("fireBullet")) {
    InvokeRepeating("fireBullet", 0f, 0.1f);
  }
}
if (Input.GetMouseButtonUp(0)) {
  CancelInvoke("fireBullet");
}
currentTime += Time.deltaTime;
if (currentTime > upgradeTime && isUpgraded == true) {
  isUpgraded = false;
}

}

private Rigidbody createBullet() {
GameObject bullet = Instantiate(bulletPrefab) as GameObject;
bullet.transform.position = launchPosition.position;
return bullet.GetComponent();
}

}

@vegetarianzombie Do you have any feedback on this? Thank you - much appreciated! :]

using version 2017.1.1f1 ( plus version ) on Mac

I loaded the final chapter code for chapter 7 and that was fine.

I doubled checked my code and started again from the beginning of chapter 7 but I am still getting the issue,

I hope these extra details help.

Hey there, without seeing your project, my guess is that the bullet prefab hasn’t been set in the project. Back in Unity, check the BobbleMarine-Body and look at the Gun component. Check to see if there is a projectile in the Bullet Prefab field.

My guess is that it is missing and that’s the reason you are getting the null exceptions. Let me know how it turns out.

Thanks!

This topic was automatically closed after 166 days. New replies are no longer allowed.