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