rabidus-test/Assets/SoundPlayer.cs

63 lines
1.4 KiB
C#
Raw Normal View History

2023-10-09 16:51:27 +03:00
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SoundPlayer : MonoBehaviour
{
private AudioSource source;
2023-10-31 14:38:42 +03:00
private Coroutine _coroutine;
private float _muteVolume;
2023-10-09 16:51:27 +03:00
private void Awake()
{
source = gameObject.AddComponent<AudioSource>();
}
public void Play(Sound sound)
{
2023-10-31 14:38:42 +03:00
_muteVolume = sound.MuteVolume;
2023-10-09 16:51:27 +03:00
source.clip = sound.Clip;
source.volume = sound.Volume;
source.pitch = sound.Pitch;
source.priority = sound.Priority;
source.playOnAwake = sound.PlayOnAwake;
source.loop = sound.Loop;
2023-10-09 17:30:55 +03:00
source.spatialBlend = sound.Zone;
2023-10-09 16:51:27 +03:00
source.Play();
2023-10-31 14:38:42 +03:00
if (!sound.Loop)
Destroy(gameObject, 30);
2023-10-09 16:51:27 +03:00
}
2023-10-27 18:07:01 +03:00
public void Stop()
{
source.Stop();
2023-10-31 14:38:42 +03:00
if (_coroutine != null)
StopCoroutine(_coroutine);
}
public void Mute(float time)
{
if (_coroutine != null)
StopCoroutine(_coroutine);
_coroutine = StartCoroutine(Mute_Coroutine(time));
}
private IEnumerator Mute_Coroutine(float time)
{
Debug.Log("Mute started");
float oldVolume = source.volume;
source.volume = _muteVolume;
yield return new WaitForSeconds(time + 1);
Debug.Log("Mute ended");
source.volume = oldVolume;
_coroutine = null;
2023-10-27 18:07:01 +03:00
}
2023-10-09 16:51:27 +03:00
}