1

可能有与此类似的问题,但我找不到任何有用的问题。

我有一个简单的脚本,其中包含一个类列表,其中包含每个元素的音频剪辑、ID 和事件系统。

我需要将该音频剪辑字段列出并按顺序播放,直到最后一个然后停止并触发事件。

这是我只有一个音频剪辑插槽的代码:(我也尝试了音频剪辑数组,但它只是播放音频剪辑数组上的第一个)

public class MainAudioManager : MonoBehaviour {


public List<soundInfo> currentsoundinfoList = new List<soundInfo>();

AudioSource audioSource;

soundInfo curentSoundInfo;

float audioLenght;


void Start () {


    audioSource = gameObject.GetComponent<AudioSource> ();

}


public void SetAudioToPlay (int ID) {


    for (int i = 0; i < currentsoundinfoList.Count; i++) {

        if (currentsoundinfoList [i].ID == ID) {

            curentSoundInfo = currentsoundinfoList[i];

            audioSource.clip = curentSoundInfo.clipToPlay;

            audioSource.Play ();

            audioLenght = audioSource.clip.length;

            StartCoroutine ("waitnigTillEbd");


            return;

        }

    }


}


IEnumerator waitnigTillEbd () {



    yield return new WaitForSeconds (audioLenght + 1f);

    curentSoundInfo.eventOnSound.Invoke ();

}


[System.Serializable]

public class soundInfo {


    public string name;

    public int ID;

    public AudioClip clipToPlay;

    public UnityEvent eventOnSound;

}

}

4

1 回答 1

0

好吧,我自己找到了解决方案。这是创建声音列表的最终结果,每个声音都单独附加了事件 onstop,也可以通过另一个事件和类的 ID 播放,供任何需要它的人使用

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

using UnityEngine.Events;


[RequireComponent(typeof(AudioSource))]

public class MainAudioManager : MonoBehaviour {


public List<soundInfo> soundList = new List<soundInfo>();

AudioSource audioSource;

soundInfo curentSoundInfo;

float audioLenght;


void Start () {


    audioSource = gameObject.GetComponent<AudioSource> ();

}


public void SetAudioToPlay (int ID) {



        for (int i = 0; i < soundList.Count; i++) {


            if (soundList [i].ID == ID) {

                curentSoundInfo = soundList [i];

                StartCoroutine(playSequencely());

                return;

        }

    }

}

  IEnumerator playSequencely () {


    yield return null;


    for (int cnt = 0; cnt < curentSoundInfo.clipsToPlay.Length; cnt++) {


        audioSource.clip = curentSoundInfo.clipsToPlay [cnt];

        audioSource.Play ();


        while (audioSource.isPlaying) {


            yield return null;

        }


        }

    //Debug.Log ("Last Audio Is Playing");

    curentSoundInfo.onStop.Invoke ();

    }

} 


[System.Serializable]

public class soundInfo {


    public string name;

    public int ID;

    [TextArea (2, 8)] public string About;

    public AudioClip[] clipsToPlay;

    //public float delayBetween;

    public UnityEvent onStop;

}
于 2019-12-05T07:23:15.740 回答