Problem with Chapter 7 Sounds - NullReferenceException for the GunFire

Hi, im having troubble when I add sound to the gunfire.

When i shoot i am getting this error:

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

Here is my gun script:

//Variables
public GameObject bulletPrefab;
public Transform launchPosition;
private AudioSource audioSource;

void fireBullet()
{
    //1 
    GameObject bullet = Instantiate(bulletPrefab) as GameObject;

    //2
    bullet.transform.position = launchPosition.position;

    //3
    bullet.GetComponent<Rigidbody>().velocity = transform.parent.forward * 100;
    audioSource.PlayOneShot(SoundManager.Instance.gunFire);
}
// Use this for initialization
void Start () {
    audioSource = GetComponent<AudioSource>();
}
// Update is called once per frame
void Update () {
    //Shoot bullet
    if (Input.GetMouseButtonDown(0))
    {
        if (!IsInvoking("fireBullet"))
        {
            InvokeRepeating("fireBullet", 0f, 0.15f);
        }
    }
    if (Input.GetMouseButtonUp(0))
    {
        CancelInvoke("fireBullet");
    }
}

And here is my Sound Manager script:

    public static SoundManager Instance = null;
public AudioClip gunFire;
public AudioClip upgradedGunFire;
public AudioClip hurt;
public AudioClip alienDeath;
public AudioClip victory;
public AudioClip elevatorArrived;
public AudioClip powerUpPickup;
public AudioClip powerUpAppear;

private AudioSource soundEffectAudio;


// Use this for initialization
void Start () {
	if (Instance = null)
    {
        Instance = this;
    } else if (Instance != this)
    {
        Destroy(gameObject);
    }

    AudioSource[] sources = GetComponents<AudioSource>();
    foreach (AudioSource source in sources)
    {
        if (source.clip == null)
        {
            soundEffectAudio = source;  
        }
    }
}

// Update is called once per frame
void Update () {
	
}

}

Nevermind, I have find out my mistake, at the sound manager I use “=” than “==”.

I will leave the topic here if someone has the same problem.
Thanks! :slight_smile:

@rafaelriva Glad you sorted it out! Cheers! :]

Thanks, I made the same mistake.

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