terminalCode Example
Playing Sounds
Playing Sounds in s&box
s&box provides both 2D and 3D sound playback through code and components.
Quick Sound Playback
CSHARP
// Play a 2D sound (UI, music, etc.)
Sound.Play("ui.click");
// Play a 3D positional sound
Sound.Play("weapons.shotgun.fire", WorldPosition);
// With volume control
Sound.Play("ambient.wind", position, volume: 0.5f);Sound Handle
Store the handle to control playback:
CSHARP
SoundHandle music = Sound.Play("music.background");
music.Volume = 0.3f;
music.Stop();Networked Sound (RPC)
CSHARP
[Rpc.Broadcast]
public static void PlaySoundAllClients(string soundName, Vector3 position)
{
Sound.Play(soundName, position);
}Audio Components
Add these to GameObjects for advanced audio:
| Component | Purpose |
|---|---|
| SoundPointComponent | Positional 3D sound at a point |
| SoundBoxComponent | Sound within a box area |
| SoundscapeTrigger | Ambient soundscapes |
| AudioListener | Override hearing position |
| VoiceComponent | Voice chat |
| LipSyncComponent | Lip sync from audio |
SoundPointComponent Example
CSHARP
public class Weapon : Component
{
[Property] public SoundEvent FireSound { get; set; }
void Fire()
{
// Create sound point
var soundPoint = Components.Create<SoundPointComponent>();
soundPoint.SoundEvent = FireSound;
soundPoint.Volume = 1.0f;
soundPoint.Play();
// Auto-destroy after sound finishes
soundPoint.GameObject.DestroyAsync(FireSound.Duration);
}
}Sound Events
Define reusable sound events in the editor:
- Create .sound asset
- Configure: file path, volume, pitch variation, distance attenuation
- Reference in code: [Property] public SoundEvent MySound { get; set; }
Was this helpful?