davidnatro
davidnatro

Reputation: 73

Audio stops instantly after loading next scene

I'm new in unity, cannot solve a problem. I have a sound and a script. On collision it should play the sound and it does so but it also loads next scene and isntantly stops the sound.

here's my code

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ScoreCounter : MonoBehaviour
{
    public GameObject Step;
    public int scoreCounter;
    public float speedGain = 0f; //-026f
    private AudioSource audioSource;
    public AudioClip Scored;

    private void OnTriggerEnter2D(Collider2D collision)
    {
        scoreCounter++;
        if (scoreCounter == 1)
        {
            speedGain = -0.235f;
        }
        if (collision.name == "gates")
        {
            scoreCounter -= 1;
            audioSource = GetComponent<AudioSource>();
            audioSource.clip = Scored;
            audioSource.Play();
        }
        speedGain -= 0.025f;
        Instantiate(Step, new Vector2(0.0f, 5.0f), Quaternion.identity);
    }
}

Upvotes: 0

Views: 2849

Answers (1)

Leoverload
Leoverload

Reputation: 1240

Unity automatically stops your sound because your audioSource is being Disabled when you start or load a new scene.

You can avoid this by using some plugins like FMOD but I will suggest the DontDestroyOnLoad() to avoid having this problem and it's an easy fix.

Firstly put the audioSource in an empty gameObject and use your script with it and add a random tag for it, like "audioObj". Then you need to call the DontDestroyOnLoad() in the Awakeof the script attached to it:

private void Awake()
 {
     DontDestroyOnLoad(transform.gameObject);
     audioSource = GetComponent<AudioSource>();
 }

In this way, you can start playing music from all the scenes without having problems or the music to stop with this simple line:

GameObject.FindGameObjectWithTag("audioObj").GetComponent<AudioScript>().PlayMusic();

And also

GameObject.FindGameObjectWithTag("audioObj").GetComponent<AudioScript>().StopMusic();

Where AudioScript is the script of your audio and PlayMusic() and StopMusic() are public functions that play and stop music, but you can do it with everything, you just need to call the GameObjec.FindGameObjectWithTag("audioObj");

Hope I helped!

Upvotes: 2

Related Questions