Как фиксировать изменение громкости устройства Unity

Рейтинг: 0Ответов: 1Опубликовано: 19.07.2023

Для игры нужно фиксировать изменение громкости на устройстве, то есть его нажатия на кнопки громкости

Ответы

▲ 0

Самый примитивный вариант: в Update сравниваешь громкость, если изменилась - вызываешь свой ивент

 // Makes Unity messages be called by both edit mode and play mode
[ExecuteAlways]

[RequireComponent(typeof(AudioSource))]
public class AudioSourceVolumeTrigger : MonoBehaviour
{
    [SerializeField]
    private AudioSource _audioSrouce;

    // In the Inspector make sure to set the event to "Editor And Runtime"
    // Default is "Runtime Only"
    public UnityEvent<float,float> OnVolumeChanged;

    private float _lastVolume;

    private void Awake()
    {
        if (!_audioSrouce) _audioSrouce = GetComponent<AudioSource>();

        _lastVolume = _audioSrouce.volume;
    }

    // PlayMode - called every frame
    // EditMode - called after every change to scene or assets
    private void Update()
    {
        // Has the volume changed?
        if (!Mathf.Approximately(_audioSrouce.volume, _lastVolume))
        {
            // invoke the event 
            OnVolumeChanged?.Invoke(_lastVolume, _audioSrouce.volume);

            // and store the new volume to compare later again
            _lastVolume = _audioSrouce.volume;
        }
    }
}