tree6316
야금야금 개발
tree6316
전체 방문자
오늘
어제
  • 분류 전체보기 (34)
    • Unity (8)
    • Language (0)
      • Java (0)
    • Web (23)
      • HTML (9)
      • CSS (3)
      • JavaScript (9)
      • JSP (2)
      • Ajax (0)
    • DB (0)
      • MySQL (0)
      • Oracle (0)
    • OS (0)
      • CentOS (0)
    • Server (1)
      • CiscoPacketTracer (1)
    • DevTool (1)
      • VMware (0)
      • IDE (1)
    • ETC (0)
    • 일상 (0)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
tree6316

야금야금 개발

유니티 사운드 매니저
Unity

유니티 사운드 매니저

2023. 12. 10. 15:08

 

https://www.youtube.com/watch?v=YPEkpwPrmPk

골드 메탈님 코드를 그대로 가져 왔습니다

 

골드 메탈님 감사합니다

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AudioManager : MonoBehaviour
{
    public static AudioManager instance;

    [Header("#BGM")]
    public AudioClip bgmClip;
    public float bgmVolume;
    AudioSource bgmPlayer;

    [Header("#SFX")]
    public AudioClip[] sfxClips;
    public float sfxVolume;
    public int channels;
    AudioSource[] sfxPlayers;
    int channelIndex;

    public enum Sfx { Dead, Hit, LevelUp = 3, Lose, Melee, Range = 7, Select, Win };

	void Awake()
    {
        instance = this;
        Init();
    }
    
    void Init()
    {
        //배경음 플레이어 초기화
        GameObject bgmObject = new GameObject("BgmPlayer"); 
        bgmObject.transform.parent = transform;
        bgmPlayer = bgmObject.AddComponent<AudioSource>();
        bgmPlayer.playOnAwake = false;
        bgmPlayer.loop = true;
        bgmPlayer.volume = bgmVolume;
        bgmPlayer.clip = bgmClip;

        //효과음 플레이어 초기화
        GameObject sfxObject = new GameObject("SfxObject");
        sfxObject.transform.parent = transform;
        sfxPlayers = new AudioSource[channels];

        for(int index = 0; index < sfxPlayers.Length; index++)
        {
            sfxPlayers[index] = sfxObject.AddComponent<AudioSource>();
            sfxPlayers[index].playOnAwake = false;
            sfxPlayers[index].volume = sfxVolume;
        }
    }

    public void PlaySfx(Sfx sfx)
    {
        for(int index = 0; index < sfxPlayers.Length; index++)
        {
            int loopIndex = (index + channelIndex) % sfxPlayers.Length;

            if (sfxPlayers[loopIndex].isPlaying)
                continue;

            int ranIndex = 0;
            if(sfx == Sfx.Hit || sfx == Sfx.Melee){
                ranIndex = Random.Range(0,2);
            }

            channelIndex = loopIndex;
            sfxPlayers[loopIndex].clip = sfxClips[(int)sfx];
            sfxPlayers[loopIndex].Play();
            break;
        }
    }
}

이거 쓰고 다른 소리 들릴 코드에

AudioManager.instance.PlaySfx(AudioManager.Sfx.Dead);

이거 쓰시면 끝입니다 감사합니다

저작자표시 (새창열림)

'Unity' 카테고리의 다른 글

NewInputSystem  (1) 2024.01.14
ObjectPool  (0) 2024.01.07
AOSFogWar  (0) 2023.12.03
Dotween 맛보기  (0) 2023.12.03
UGS 맛보기  (0) 2023.11.20
    tree6316
    tree6316
    야금야금 개발하는 블로그입니다.

    티스토리툴바