Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using UniRx;
- using UnityEngine;
- namespace KotonohaAnone.Presenter
- {
- public class BeatTransmitter : MonoBehaviour
- {
- [SerializeField] private AudioSource audioSource;
- [SerializeField] private float bpm;
- private readonly Subject<Unit> beatSubject = new Subject<Unit>();
- // 曲の何ビート目か(前Update時)
- private int previousBeatCount = 0;
- private void Update()
- {
- float beatTime = 60f / bpm;
- int currentBeatCount = Mathf.FloorToInt(audioSource.time / beatTime);
- if(currentBeatCount != previousBeatCount)
- {
- beatSubject.OnNext(Unit.Default);
- }
- previousBeatCount = currentBeatCount;
- }
- private void OnDestroy()
- {
- beatSubject.Dispose();
- }
- // ビートを観測する
- // 1拍ごとに発行される
- public IObservable<Unit> ObserveBeat()
- {
- return beatSubject;
- }
- }
- // 利用側
- class Usage : MonoBehaviour
- {
- void SomeMethod()
- {
- BeatTransmitter beat = GetComponent<BeatTransmitter>();
- beat.ObserveBeat()
- .Subscribe(_=>
- {
- // ビートごとに何かする
- })
- .AddTo(this);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement