The question is answered, right answer was accepted
How Do I Add An Audio File To A Button
I Want It So That When I Tap On The Button On An Android Phone Or Tablet It Plays An Audio File
Hi, please use normal text formatting. Starting every word with a capital letter is very annyoing to read and confusing when used in long sentences. ;)
You can use the event system of the UI. There is no need for a script.
Check Ali's anwer.
Answer by Ali-hatem · Apr 13, 2016 at 11:07 AM
you don't need any code for that if you don't have to change clip @ runtime but you have to know how to use On Click Event if not see this Make buttons do something
then attach an AudioSource to the button & add audio clip the AudioSource then create On Click event then drag & drop the button to the On Click empty field then open the drop down menu next to it highlight the AudioSource then other panel will open select Play();
Answer by KaushikRahul · Apr 13, 2016 at 10:21 AM
You can add an AudioSource and attach it to any GameObject.
Uncheck PlayOnAwake.
Uncheck Loop as well if you don't want it to play in a loop.
Get reference of that GameObject in your script.
Play it when needed.
Script:
using UnityEngine;
using System.Collections;
public class SoundManager : MonoBehaviour {
public AudioSource sound;
public AudioClip clipSound;
public bool playSound;
void Start()
{
sound.clip = clipSound;
playSound= false;
}
void Update ()
{
if (playSound)
{
sound.Play();
playSound= false;
}
}
}
You can update the value of the bool whenever you want to play sound, i.e. on your click on button.
:) :)
Its the most basic version, which a first timer can use to get around with.
There are multiple ways to achieve the same.
I do this in small projects where I don't have to handle n number of sounds but 4-5.
:) :)
(Sorry for the previous comment, it was bugged)
Both of you are right, Ali is just giving tips for optimizing.
You don't need to make the AudioSource public, since no other script needs to access it.
[Serializable] AudioSource sound;
You could use a public function and hook it up to the button:
public void PlayButtonSound() { sound.Play(); }
But that is just a step of optimization. Your code wouldn't check something on every Update tick that way. Using bools for if checks and switching operations is not "wrong".
There are many ways to answer this question and it is up to the OP to choose and accept the answer that suits him best. That doesn't mean it is the best, though ;)