Common examples are:
- background music
- button sounds
- pickup sounds
- jump sounds
- hit or impact sounds
- short ambience loops
An AudioSource does not create audio by itself. It needs an audio clip, such as
a .wav, .mp3, or .ogg file, assigned to its Clip field.
Add an Audio Source in the Editor
Start with the full editor workflow:
- Import or place your audio file under the project's
Assetsfolder. - Select the GameObject that should play the sound.
- In the Inspector, choose
Add Component. - Open
Audio. - Choose
Audio Source. - In the new
Audio Sourcecard, assign theClip.
You can assign the clip in either of these ways:
- click the
Clipfield and choose an audio asset from the picker - drag an audio asset from the Assets panel onto the
Clipfield
After assigning a clip, use the Preview and Stop buttons in the Inspector to
audition the sound with the current Volume and Pitch values.
Understand the Main Settings
Clip is the audio file the source will play.
If this field is empty, the source has nothing to play. If the referenced file is missing, the Inspector shows a missing-clip warning.
Play On Awake controls whether the sound starts automatically when the scene
starts.
Turn it on for background music or ambient loops. Turn it off for sounds that should be triggered by gameplay code.
Loop controls whether the sound repeats after it finishes.
Turn it on for music and ambience. Leave it off for short sound effects.
Volume controls how loud this source is.
Use 1.0 for full volume, 0.5 for half volume, and 0.0 for silence.
Pitch controls how high or low the sound plays.
Use 1.0 for the original pitch. Higher values play higher and faster. Lower
values play lower and slower.
Play a Sound from PHP
Put this code in a Behaviour attached to a GameObject that has an
AudioSource component.
<?php
namespace Game\Scripts;
use Lenga\Engine\Core\AudioSource;
use Lenga\Engine\Core\Behaviour;
use Lenga\Engine\Core\Input;
use Lenga\Engine\Core\KeyCode;
final class JumpSound extends Behaviour
{
private ?AudioSource $audio = null;
public function start(): void
{
$this->audio = $this->gameObject->getComponent(AudioSource::class);
}
public function update(): void
{
if (Input::getKeyDown(KeyCode::SPACE)) {
$this->audio?->play();
}
}
}
This script does three things:
- It gets the
AudioSourceattached to the same GameObject. - It checks whether the player pressed the Space key.
- It calls
play()on the audio source.
Recommended Workflow
Use the editor for authored defaults:
- assign the clip
- set
Play On Awake - set
Loop - tune
Volume - tune
Pitch
Use PHP for gameplay timing:
- play pickup sounds when an item is collected
- play jump sounds when the character jumps
- stop or change music when switching scenes
- trigger UI sounds when a menu button is selected