<html lang='es' xmlns='http://www.w3.org/1999/xhtml' xmlns:b='http://www.google.com/2005/gml/b' xmlns:data='http://www.google.com/2005/gml/data' xmlns:expr='http://www.google.com/2005/gml/expr'></html> Gestor de audio global y GameManager - Videojuegos con Unity

Gestor de audio global y GameManager

 Gestor de audio global y GameManager


## Tutorial 3: Gestor de Audio Global (`AudioManagerH`)
### ¿Para qué sirve?

Administra la reproducción centralizada de todos los sonidos del juego mediante un patrón modular, permitiendo invocar cualquier efecto de audio por su nombre de forma instantánea.  


### Código del Script (`AudioManagerH`)
```csharp
using UnityEngine;
using System;

public class AudioManagerH : MonoBehaviour
{
    public Sound[] sounds;
    public static AudioManagerH instance;

    private void Awake()
    {
        if (instance == null)
        {
            instance = this;
            DontDestroyOnLoad(gameObject);
        }
        else
        {
            Destroy(gameObject);
            return;
        }

        foreach (Sound s in sounds)
        {
            s.source = gameObject.AddComponent<AudioSource>();
            s.source.clip = s.clip;
            s.source.volume = s.volume;
            s.source.pitch = s.pitch;
            s.source.loop = s.loop;
        }
    }

    public void Play(string name)
    {
        Sound s = Array.Find(sounds, sound => sound.name == name);
        if (s == null)
        {
            Debug.LogWarning($"AudioManager: El sonido '{name}' no fue encontrado.");
            return;
        }
        s.source.Play();
    }
}
```

### Implementación
1. Crea un GameObject vacío en tu escena inicial llamado `AudioManager`.
2. Añade este script y rellena el array `Sounds` con los clips de audio necesarios.


 

 

## Tutorial 4: El Núcleo del Juego (`ManagerGame`)

### ¿Para qué sirve?

Controla el flujo global del videojuego: puntuaciones actuales, récords guardados de forma persistente con `PlayerPrefs`, transiciones de nivel y gestión de estados de victoria o derrota.

 

### Código del Script (`ManagerGame.cs`)
```csharp
using System.Collections;
using UnityEngine;

public class ManagerGame : MonoBehaviour
{
    public static ManagerGame singlenton;

    [Header("Puntuación y Progreso")]
    public int bestScore;
    public int currentScore;
    public int currentLevel = 0;

    private AudioManagerH audioManager;
    private HelixManager helixManager;
    private BallManager ballManager;

    private void Awake()
    {
        if (singlenton == null)
        {
            singlenton = this;
        }
        else if (singlenton != this)
        {
            Destroy(gameObject);
            return;
        }

        bestScore = PlayerPrefs.GetInt("HighScore", 0);
    }

    private void Start()
    {
        audioManager = FindFirstObjectByType<AudioManagerH>();
        helixManager = FindFirstObjectByType<HelixManager>();
        ballManager = FindFirstObjectByType<BallManager>();
    }

    public void NextLevel()
    {
        currentLevel++;
        StartCoroutine(NextLevelRoutine());
        if (audioManager != null) audioManager.Play("Ta Da");
    }

    private IEnumerator NextLevelRoutine()
    {
        yield return new WaitForSeconds(0.25f);
        if (ballManager != null) ballManager.ResetBall();
        if (helixManager != null) helixManager.LoadStage(currentLevel);
    }

    public void RestartLevel()
    {
        StartCoroutine(ResetLevelRoutine());
        if (audioManager != null) audioManager.Play("GameOver");
    }

    private IEnumerator ResetLevelRoutine()
    {
        yield return new WaitForSeconds(0.45f);
        currentScore = 0;
        if (ballManager == null) ballManager = FindFirstObjectByType<BallManager>();
        if (helixManager == null) helixManager = FindFirstObjectByType<HelixManager>();

        if (ballManager != null) ballManager.ResetBall();
        if (helixManager != null) helixManager.LoadStage(currentLevel);
    }

    public void AddScore(int scoreToAdd)
    {
        currentScore += scoreToAdd;
        if (currentScore > bestScore)
        {
            bestScore = currentScore;
            PlayerPrefs.SetInt("HighScore", bestScore);
            PlayerPrefs.Save();
        }
    }
}
```

### Implementación
Asocia este script a un objeto controlador global
persistente en tu escena de juego principal.

 


No hay comentarios

Imágenes del tema: merrymoonmary. Con la tecnología de Blogger.