I have a player GO with an AudioSource component to play different sounds when hit or killed.
When testing my play scene in editor it works great, but when I reload the scene (main scene > gameover > Title Scene > Main Scene) I get ArgumentNullException when calling PlayOneShot.
I added a setter to see when the Audio source gets set to null but it only triggers in my Awake function and is really set to the correct value.
Breakpoints troubleshooting reveals this behaviour :
Awake() => AudioSource has a value, references the component from GetComponent();
AudioSource setter triggered with the debug log correctly displaying in console
When OnPlayerHit is triggered, AudioSource is now null, but the setter was never called.
Both AudioClips are set in inspector and have correct value .
public class PlayerHealth : MonoBehaviour
{
[SerializeField]
IntVariable playerStartHp;
[SerializeField]
IntVariable playerCurrentHp;
[SerializeField]
AudioClip audioHit;
[SerializeField]
AudioClip audioDead;
AudioSource source;
public AudioSource Source {
get { return source; }
set
{
source = value;
Debug.Log($"audio source set to {value}");
}
}
private void Awake()
{
Source = GetComponent<AudioSource>();
playerCurrentHp.valueDown += OnPlayerHit;
playerCurrentHp.value = playerStartHp.value;
}
//private void OnDestroy()
//{
// audioDead.Play();
//}
void OnPlayerHit()
{
if (playerCurrentHp.value == 0)
{
StartCoroutine(DieCoroutine());
}
else Source.PlayOneShot(audioHit);
}
IEnumerator DieCoroutine()
{
Source.PlayOneShot(audioDead);
while (Source.isPlaying)
{
yield return null;
}
Destroy(gameObject);
}
}