美文网首页Unity x Sound
Unity x Brackeys | introduction

Unity x Brackeys | introduction

作者: zitaoye | 来源:发表于2021-01-27 16:25 被阅读0次

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");

相关文章

网友评论

    本文标题:Unity x Brackeys | introduction

    本文链接:https://www.haomeiwen.com/subject/sbsazktx.html