0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Unity】音が鳴るオブジェクト用のスクリプト

Posted at

Active状態を変更すると鳴動し、アイドル状態用に別のオブジェクトも設定できるスクリプトです。

OnEnable時にはUniTaskを使用しています。
OnDisible側ではAudioSourceが同時にDisibleになった場合、音が鳴らなくなってしまうため、PlayClipAtPointを使用して、音を鳴らす別のオブジェクトを一時的に生成する形で実装しています。

SEObject.cs
using UnityEngine;
using Cysharp.Threading.Tasks;

public class SEObject : MonoBehaviour
{
    private AudioSource _audioSource; // 同じゲームオブジェクトにAudioSourceをアタッチしておく
    public AudioClip _enableSE;
    public AudioClip _IdleSE;
    public AudioClip _disibleSE;

    private void Awake()
    {
        _audioSource = GetComponent<AudioSource>();
    }

    /// <summary>
    /// _audioSourceが設定されていれば、表示SEを鳴らしてからアイドルSEを鳴らす。
    /// </summary>
    /// <returns></returns>
    private async UniTask OnEnable()
    {
        if (!_audioSource)
            return;

        _audioSource.PlayOneShot(_enableSE);

        // SE再生待ち
        await UniTask.WaitUntil(() => _audioSource.isPlaying);

        // SE再生終了待ち
        await UniTask.WaitWhile(() => _audioSource.isPlaying);

        // アイドルSE再生
        _audioSource.clip = _IdleSE;
        _audioSource.loop = true;
        _audioSource.Play();
    }

    private async UniTask OnDisable()
    {
        // アイドルSEを止める
        _audioSource?.Stop();

        // SE再生終了待ち
        if (_disibleSE)
            // SEを一度鳴らすと消えるオブジェクトを生成
            AudioSource.PlayClipAtPoint(_disibleSE, transform.position);
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?