Sound + somewhat game loop

This commit is contained in:
Crizomb 2025-01-28 23:00:52 +01:00
parent 29e5e48aee
commit 1d6a879755
33 changed files with 1572 additions and 595 deletions

View file

@ -10,7 +10,7 @@ public class MonoBehaviourSingletonPersistent<T> : MonoBehaviour
if (Instance == null) {
Instance = this as T;
Instance.name = typeof(T).Name;
DontDestroyOnLoad (this);
DontDestroyOnLoad (gameObject);
} else {
Destroy (gameObject);
}

View file

@ -7,12 +7,12 @@ using UnityEngine.SceneManagement;
public class GameManager : MonoBehaviourSingletonPersistent<GameManager>
{
[SerializeField] private List<string> levelNames;
[SerializeField] private List<string> levelMusics;
[SerializeField] private List<int> levelsMoney;
int current_level = -1;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
GoNextLevel();
}
// Update is called once per frame
@ -57,6 +57,7 @@ public class GameManager : MonoBehaviourSingletonPersistent<GameManager>
current_level++;
SetGlobals(current_level);
SceneManager.LoadScene(levelNames[current_level]);
SoundManager.Instance.PlayMusic(levelMusics[current_level]);
}
throw new Exception("Bro there is no next level like stop pls");

View file

@ -1,36 +1,61 @@
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Random = UnityEngine.Random;
[Serializable]
public class SoundEntry
{
public string Key;
public AudioClip Value;
}
public class SoundManager : MonoBehaviourSingletonPersistent<SoundManager>
{
// Audio players components.
public AudioSource EffectsSource;
public AudioSource MusicSource;
public Dictionary<string, AudioClip> Sounds;
// Play a single clip through the sound effects source.
public void Play(AudioClip clip)
public List<SoundEntry> SoundsList;
private Dictionary<string, AudioClip> soundsDictionary;
new void Awake()
{
EffectsSource.clip = clip;
base.Awake();
// Convert the List to a Dictionary at runtime for easier access
soundsDictionary = new Dictionary<string, AudioClip>();
foreach (var entry in SoundsList)
{
if (!soundsDictionary.ContainsKey(entry.Key))
{
soundsDictionary.Add(entry.Key, entry.Value);
}
}
}
private AudioClip GetSound(string key)
{
print(soundsDictionary.Count);
AudioClip clip = soundsDictionary.TryGetValue(key, out var value) ? value : null;
if (clip == null)
{
Debug.LogError($"Sound {key} not found");
}
return clip;
}
public void Play(string keyName)
{
EffectsSource.clip = GetSound(keyName);
EffectsSource.Play();
}
// Play a single clip through the music source.
public void PlayMusic(AudioClip clip)
public void PlayMusic(string keyName)
{
MusicSource.clip = clip;
MusicSource.clip = GetSound(keyName);
MusicSource.Play();
}
// Play a random clip from an array, and randomize the pitch slightly.
public void RandomSoundEffect(params AudioClip[] clips)
{
int randomIndex = Random.Range(0, clips.Length);
EffectsSource.clip = clips[randomIndex];
EffectsSource.Play();
}
}