Introduction
The Audio Source component plays sounds in your game. It lets you add music, sound effects, or voices to objects.
Jump into concepts and practice - no test required
The Audio Source component plays sounds in your game. It lets you add music, sound effects, or voices to objects.
AudioSource audioSource = gameObject.AddComponent<AudioSource>(); audioSource.clip = yourAudioClip; audioSource.Play();
AudioSource audioSource = gameObject.AddComponent<AudioSource>(); audioSource.clip = jumpSound; audioSource.Play();
AudioSource audioSource = GetComponent<AudioSource>();
audioSource.volume = 0.5f;
audioSource.Play();audioSource.loop = true; audioSource.Play();
This script adds an AudioSource to the object it is attached to. When the game starts, it plays the assigned sound clip once.
using UnityEngine;
public class PlaySoundOnStart : MonoBehaviour
{
public AudioClip soundClip;
private AudioSource audioSource;
void Start()
{
audioSource = gameObject.AddComponent<AudioSource>();
audioSource.clip = soundClip;
audioSource.Play();
}
}Make sure your AudioClip is assigned in the Inspector or via code before playing.
Use the loop property to repeat sounds like music.
You can control volume, pitch, and spatial blend for 3D sound effects.
The Audio Source component plays sounds attached to game objects.
Assign an AudioClip and call Play() to hear the sound.
You can control volume, looping, and other sound settings on the AudioSource.
Audio Source component in Unity?Play().AudioSource audioSource = gameObject.AddComponent<AudioSource>(); audioSource.clip = someClip; audioSource.loop = true; audioSource.volume = 0.5f; audioSource.Play();What will happen when this code runs?
AudioSource audioSource; audioSource.clip = clip; audioSource.Play();
audioSource is declared but never assigned an Audio Source component instance.audioSource.clip without initialization causes a runtime error (null reference).loop property is set to true.audioSource.loop = false; disables looping, so the sound plays only once.