Hi
I’m trying to make two difference method to play sounds. first, load a sound file, Second, play specific sound.
here is my script.
using UnityEngine;
using UnityEngine.Audio;
public class mainUgame : MonoBehaviour {
private AudioSource click_button; // one AudioSource
public AudioSource audios; // empty gameobject with three AudioSources
void Start () {
click_button = Resources.Load ("audio/UI/button_sound") as AudioSource;
}
// Update is called once per frame
void Update () {
if (Input.GetButtonUp("xbox a")) {
click_button.Play();
}
if (Input.GetButtonUp("xbox y")) {
//audios play audio 1
}
if (Input.GetButtonUp("xbox x")) {
//audios play audio 2
}
if (Input.GetButtonUp("xbox b")) {
//audios play audio 3
}
}//end
Here is a better way to set up your class. Have a single audio source, and a struct that defines what button triggers what sound. Then you can expand it to how ever many buttons and audio clips you need.
[RequireComponent(typeof(AudioSource))]
public class AudioPlayer : MonoBehaviour
{
[System.Serializable]
public struct AudioInfo
{
public AudioClip clip;
public string inputButton;
public float volumeScale;
}
public AudioInfo[] audioButtons;
private AudioSource audioSource;
private void Awake()
{
audioSource = GetComponent<AudioSource>();
}
private void Update()
{
for (int i = 0; i < audioButtons.Length; i++)
{
var info = audioButtons[i];
if (Input.GetButtonUp(info.inputButton))
{
Play(info);
}
}
}
private void Play(AudioInfo info)
{
audioSource.PlayOneShot(info.clip, info.volumeScale);
}
}
This way you just edit the fields on your GameObject with this script attached, and nothing is hardcoded.