Unity x Brackeys | introduction to AUDIO in Unity

https://www.youtube.com/watch?v=6OT43pvUyfY&t=9s

使用单例来进行管理

using UnityEngine.Audio;
using UnityEngine;
using System;

public class AudioManager: MonoBehaviour{
  public Sound[] sounds;
  public static AudioManager instance;

void Awake(){
    if(instance == null) 
        instance = this;
    else {
      Destroy(gameObject);
      return;
    }

    DonDestroyOnLoad(gameObject);


    foreach(Sound s in sounds){
    s.source = gameObject.AddComponent<AudioSource>();
    s.source.clip = s.clip;

    s.source.volume = s.volume;
    s.source.pitch = s.pitch;
    s.source.loop = s.loop;
  }

  public void Play(string name){
    Sound s = Array.Find(sounds, sound => sound.name == name);
    if(s == null){
      Debug.LogWarning("Sound:"+  name + "not found! ");
      return;
    }
    
    s.source.play();
  }

  }

}


创建sound

using UnityEngine.Audio;
using UnityEngine;

[System.Serializable]
public class Sound{

  public string name;
  public AudioClip clip;

  [Range(0f,1f)]
  public float volume;
   [Range(0f,3f)]
  public float pitch;

  [HideInInspecetor]
  public AudioSource source;

  public bool loop;

}

···

调用

FindObjectOfType<AudioManager>().Play("PlayDeath");

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容