playing sound on certain condition on object
using UnityEngine;
using System.Collections;
public class UIsoundEffect : MonoBehaviour {
PlayerHP health;
Ammo ammoSE; //SE = Sound Effect
AudioSource lowHPSE;
AudioSource lowAmmoSE;
void Start() {
AudioSource[] audios = GetComponents<AudioSource> ();
lowHPSE = audios [0];
lowAmmoSE = audios [1];
}
void Update () {
AlmostDead ();
lowAmmoLeft ();
}
void AlmostDead () {
if (health.currentHP == health.healthCritical) {
lowHPSE.Play ();
}
}
void lowAmmoLeft () {
if (ammoSE.currentAmmo == ammoSE.ammoLow) {
lowAmmoSE.Play ();
}
}
}
This worked perfectly fine until a few days ago (except not playing second audio). But now, for some reason, it doesn't play at all. I didn't even touch anything. I saved it a few days ago, closed the project, re-opened it today, and it's not working. Console says object null reference, but when it was working a few days ago, it said same thing, yet it still worked.
I'm going crazy here. Why is it not working? I considered recreating entire scene but I've come too far to re-do everything.
Answer by ThePersister · Nov 28, 2016 at 12:51 PM
You have a health variable and an ammoSE variable, neither of which you set, and they're private, so those are probably null.
Try changing your Start method to:
void Start() {
AudioSource[] audios = GetComponents<AudioSource> ();
lowHPSE = audios [0];
lowAmmoSE = audios [1];
health = GetComponent<PlayerHP>();
ammoSE = GetComponent<Ammo>();
}
I hope that helps, if it does, please accept my answer! It'd be much appreciated.
If it doesn't, please show the null reference error, to clarify what line the error is thrown. Because alternatively, you could have less than 2 or 0 AudioSource components on the object and that would throw null references too.
Best of luck!
Cheers,
ThePersister
Thanks! It now works without error and also plays in order as well!
Your answer
Follow this Question
Related Questions
Master Audio source volume control with slider 1 Answer
Using RayCast to see if button clicked 1 Answer
In what situation Component.gameObject method throws NullReferenceException? 2 Answers
OnTriggerEnter2D not working 1 Answer
Help to play music whenever the character enters a GameObject... 1 Answer