Make a Music Box in Skyrim.
Steps:
Released mod: BG3 Music Box
- Attach this script to an activator.
- Music can be Turned on/off.
- The music track is actually “Sound” in Creation Kit, Not “Music”. Reason: Music will override each other, but Sound won’t.
- Music volume changes based on Player distance.
- *Not a 3D Sound setting.
Script:
1Scriptname BG3MusicBoxScript extends ObjectReference2
3Sound Property MusicSound Auto4bool Property isPlaying = false Auto5Int instanceID = -1 ; Initialize with an invalid ID6
7Float Property MaxDistance = 3000.0 Auto ; Set range for longer fade-out8Float Property CheckInterval = 0.25 Auto ; Reduced interval for even smoother updates9
10Event OnActivate(ObjectReference akActionRef)11 if akActionRef == Game.GetPlayer()12 if isPlaying13 ; Stop the sound instance using the global function14 if instanceID != -115 Sound.StopInstance(instanceID)16 endif17 isPlaying = false18 else19 ; Play the sound and store the instance ID20 instanceID = MusicSound.Play(self)21 if instanceID != -122 isPlaying = true23 ; Start checking distance24 RegisterForSingleUpdate(CheckInterval)25 endif26 endif27 endif28EndEvent29
30Event OnUpdate()31 if isPlaying32 ; Calculate distance from player33 float distance = Game.GetPlayer().GetDistance(self)34
35 ; Calculate volume based on distance with a smoother transition36 float volume = 1.0 - (distance / MaxDistance) ; Linear fade for realistic transition37
38 ; Clamp volume between 0.0 and 1.039 if volume < 0.040 volume = 0.041 elseif volume > 1.042 volume = 1.043 endif44
45 ; Set the sound volume46 Sound.SetInstanceVolume(instanceID, volume)47
48 ; Schedule next update49 RegisterForSingleUpdate(CheckInterval)50 endif51EndEvent
Links: