My code works more or less as expected, but if I land on the finish pad and crash at the same time (right on the edge or fall over), the next level is loaded WITHOUT the saved audioClips in the variables and returns a null AudioClip error. How do I make sure that they stay?
using UnityEngine;
using UnityEngine.SceneManagement;
public class CollisionHandler : MonoBehaviour
{
AudioSource audioSource;
[HideInInspector] public int currentSceneIndex;
[SerializeField] private float delaySec = 1.5f;
//controls crash sound and volume
[SerializeField] private AudioClip crashSound;
[SerializeField] private float crashVol = 0.1f;
//victory sound and volume
[SerializeField] private AudioClip victorySound;
[SerializeField] private float victoryVol = 0.8f;
void Start() {
audioSource = GetComponent<AudioSource>();
if (audioSource == null) audioSource = gameObject.AddComponent<AudioSource>();
}
private void OnCollisionEnter(Collision other)
{
switch (other.gameObject.tag) // checks the collided object's tag
{
case "Friendly":
Debug.Log("Safe!");
break;
case "Finish":
Debug.Log("Finished!");
StartSuccess();
break;
case "Boost":
Debug.Log("Boost!");
break;
case "Boundary":
Debug.Log("Wall!");
break;
default:
Debug.Log("Hit!");
startCrash();
break;
}
}
private void StartSuccess()
{
// add SFX and particles
audioSource.PlayOneShot(victorySound, victoryVol); // plays the sound and volume from the audioSource component
GetComponent<PlayerMovement>().enabled = false;
Invoke(nameof(loadLevel), delaySec);
}
private void startCrash() {
// add SFX and particles
audioSource.PlayOneShot(crashSound, crashVol);
GetComponent<PlayerMovement>().enabled = false; //disables player movement script
Invoke(nameof(ReloadLevel), delaySec); // no longer reliant on string
}