V
V
vkvk2020-12-13 22:01:19
Unity
vkvk, 2020-12-13 22:01:19

What to do if the background music is duplicated?

Hello! I'm making my first game and I'm having a big problem with the sound. When I enter the stage where the music should be created, it is duplicated for me. That is, when I go to that stage several times, the music starts to clone and play at the same time. I roughly understand what needs to be done, but I don’t know what to add in the condition when the music is on. Help me please!

here is the code:

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

public class MusicCntrl : MonoBehaviour
{
    public AudioSource audio;
    // Start is called before the first frame update
    void Start()
    {
        audio = GetComponent<AudioSource>();
    }

    // Update is called once per frame
    void Update()
    {
        DontDestroyOnLoad(transform.gameObject);
        if (audio.isPlaying)
        {
            
        }
        else
        {
            audio.Play();
        }
    }
}


In unity itself, I created an object into which I put the script, in the audio field I put the AudioSource of this object. But unfortunately I don't know what to do next. I looked at the unity documentation, videos on YouTube, but I did not find anything.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
mopsicus, 2020-12-14
@mopsicus

It is duplicated because the object is not deleted
DontDestroyOnLoad(transform.gameObject);
for some reason also in the update...

M
muso-alt, 2020-12-14
@muso-alt

Create a coroutine that will wait for the music to finish playing, and call audio.clip.length while waiting in the coroutine

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question