Concept Flow - Playing sound effects
Start
Load AudioClip
Get AudioSource
Call PlayOneShot()
Sound plays
End
This flow shows how Unity plays a sound effect by loading the sound, getting the AudioSource, and then playing it.
Jump into concepts and practice - no test required
AudioSource audioSource;
AudioClip clip;
void PlaySound() {
audioSource.PlayOneShot(clip);
}| Step | Action | AudioSource State | Sound Played | Output |
|---|---|---|---|---|
| 1 | AudioSource and AudioClip assigned | assigned AudioSource, clip loaded | No | No sound yet |
| 2 | PlaySound() called | playing sound | Yes | Sound effect starts playing |
| 3 | Sound plays fully | playing sound | Yes | Sound effect ends |
| 4 | End of PlaySound() | audioSource ready | No | Ready for next sound |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | Final |
|---|---|---|---|---|---|
| audioSource | null | assigned AudioSource | playing sound | playing sound | ready |
| clip | null | assigned AudioClip | assigned AudioClip | assigned AudioClip | assigned AudioClip |
Playing sound effects in Unity: - Get an AudioSource and load an AudioClip - Use audioSource.PlayOneShot(clip) to play sound once - Multiple PlayOneShot calls can overlap sounds - AudioClip must be assigned or no sound plays - AudioSource remains ready after playing
AudioSource.Play() plays the assigned clip but can interrupt sounds if called repeatedly.AudioSource.PlayOneShot() plays a clip once without stopping other sounds.AudioSource audioSource;.new AudioSource() is not used directly; AudioSource() is not a constructor; assigning AudioClip to AudioSource variable is invalid.public class SoundTest : MonoBehaviour {
public AudioSource audioSource;
public AudioClip clip;
void Start() {
audioSource.PlayOneShot(clip);
audioSource.PlayOneShot(clip);
}
}PlayOneShot plays the clip immediately without stopping other sounds, allowing overlap.public class PlaySound : MonoBehaviour {
public AudioSource audioSource;
public AudioClip clip;
void Update() {
if (Input.GetKeyDown(KeyCode.Space)) {
audioSource.Play(clip);
}
}
}AudioSource.Play() does not accept parameters; it plays the assigned clip only.AudioSource.PlayOneShot(clip) to play a clip passed as argument.public AudioSource audioSource;
public AudioClip jumpSound;
public AudioClip hitSound;
void PlayJump() {
// ???
}
void PlayHit() {
// ???
}PlayOneShot() allows playing multiple clips without interrupting each other.audioSource.PlayOneShot(jumpSound); in PlayJump and audioSource.PlayOneShot(hitSound); in PlayHit. uses PlayOneShot correctly; Assign audioSource.clip = jumpSound; then call audioSource.Play(); in PlayJump; same for hitSound in PlayHit. overwrites clip and may cut sounds; Create new AudioSource for each sound effect and call Play() on each. is inefficient; Use audioSource.Play(); without assigning clips. plays nothing.