0

¿Cómo puedo reproducir un audio en Unity de tal manera que cuando ocurra un cambio de escena el audio siga reproduciéndose sin ser interrumpido?

1

1 respuesta 1

1

Con el patrón de diseño singleton puedes hacer que los GameObjects se mantengan entre escenas.

using UnityEngine;
using System.Collections;

    using System.Collections.Generic;       //Allows us to use Lists. 

    public class GameManager : MonoBehaviour
    {

        public static GameManager instance = null;              //Static instance of GameManager which allows it to be accessed by any other script.
        private BoardManager boardScript;                       //Store a reference to our BoardManager which will set up the level.
        private int level = 3;                                  //Current level number, expressed in game as "Day 1".

        //Awake is always called before any Start functions
        void Awake()
        {
            //Check if instance already exists
            if (instance == null)

                //if not, set instance to this
                instance = this;

            //If instance already exists and it's not this:
            else if (instance != this)

                //Then destroy this. This enforces our singleton pattern, meaning there can only ever be one instance of a GameManager.
                Destroy(gameObject);    

            //Sets this to not be destroyed when reloading scene
            DontDestroyOnLoad(gameObject);

            //Get a component reference to the attached BoardManager script
            boardScript = GetComponent<BoardManager>();

            //Call the InitGame function to initialize the first level 
            InitGame();
        }

        //Initializes the game for each level.
        void InitGame()
        {
            //Call the SetupScene function of the BoardManager script, pass it current level number.
            boardScript.SetupScene(level);

        }
    }

En este ejemplo de Writing the Game Manager se puede notar que en método Awake pregunta si la hay una instancia en escena, si es verdadero quiere decir que esta es la instancia y si es falso borrara esta instancia y al final mantendrá el GameObject que contenga esta clase en escenas.

Ya que al cargar una escena todos los GameObject de la escena anterior son destruidos, el método DontDestroyOnLoad(gameObject) evita que ese sea destruido.

Esto lo puedes agregar en el script donde manejes el audio.

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.