66 lines
2.6 KiB
C#
66 lines
2.6 KiB
C#
using Cysharp.Threading.Tasks;
|
|
using UnityEngine;
|
|
|
|
|
|
namespace BrewMonster.Scripts
|
|
{
|
|
public class TemporaryBackgroundMusic : MonoBehaviour
|
|
{
|
|
public string backgroundMusicPath;
|
|
public string ambientSoundPath;
|
|
|
|
public AudioSource backgroundMusicSource;
|
|
public AudioSource ambientSoundSource;
|
|
// Start is called once before the first execution of Update after the MonoBehaviour is created
|
|
void Start()
|
|
{
|
|
// get the HostPlayer
|
|
SetupAudioSources().Forget();
|
|
}
|
|
|
|
private async UniTask SetupAudioSources()
|
|
{
|
|
// get the HostPlayer
|
|
var hostPlayer = CECGameRun.Instance.GetHostPlayer();
|
|
|
|
while (hostPlayer == null)
|
|
{
|
|
await UniTask.DelayFrame(1);
|
|
hostPlayer = CECGameRun.Instance.GetHostPlayer();
|
|
}
|
|
|
|
// attach 2 audio source gameobjects to the host player
|
|
GameObject backgroundMusicObject = new GameObject("BackgroundMusic");
|
|
backgroundMusicSource = backgroundMusicObject.AddComponent<AudioSource>();
|
|
backgroundMusicObject.transform.parent = hostPlayer.transform;
|
|
backgroundMusicObject.transform.localPosition = Vector3.zero;
|
|
backgroundMusicObject.transform.localRotation = Quaternion.identity;
|
|
backgroundMusicObject.transform.localScale = Vector3.one;
|
|
|
|
GameObject ambientSoundObject = new GameObject("AmbientSound");
|
|
ambientSoundSource = ambientSoundObject.AddComponent<AudioSource>();
|
|
ambientSoundObject.transform.parent = hostPlayer.transform;
|
|
ambientSoundObject.transform.localPosition = Vector3.zero;
|
|
ambientSoundObject.transform.localRotation = Quaternion.identity;
|
|
ambientSoundObject.transform.localScale = Vector3.one;
|
|
|
|
await PlayBackgroundMusic();
|
|
}
|
|
|
|
private async UniTask PlayBackgroundMusic()
|
|
{
|
|
// use AddressableManager to load the background music and ambient sound
|
|
var backgroundMusicClip = await AddressableManager.Instance.LoadAudioClipAsync(backgroundMusicPath.ToLower());
|
|
var ambientSoundClip = await AddressableManager.Instance.LoadAudioClipAsync(ambientSoundPath.ToLower());
|
|
|
|
// play the background music and ambient sound
|
|
backgroundMusicSource.clip = backgroundMusicClip;
|
|
backgroundMusicSource.loop = true;
|
|
backgroundMusicSource.Play();
|
|
ambientSoundSource.clip = ambientSoundClip;
|
|
ambientSoundSource.loop = true;
|
|
ambientSoundSource.Play();
|
|
}
|
|
}
|
|
}
|