I’m currently scripting a custom Animate script for my game and It’s supposed to play a footstep sound when the player walks. But as said in the title of this topic the sound is only playing once in three.
Here’s the code I’m using to play the sound.
function Footsteps:PlayFootstepSound(foot: Instance, material: string)
if not foot then return end
local sounds = Footsteps.Sounds[material]
if not sounds then return end
local soundId = sounds[Random.new():NextInteger(1, #sounds)]
if not soundId or soundId == lastFootstepSound then
Footsteps:PlayFootstepSound(foot, material)
return
end
lastFootstepSound = soundId
local SoundEffect = Instance.new("Sound")
SoundEffect.SoundId = soundId
SoundEffect.RollOffMaxDistance = 100
SoundEffect.RollOffMinDistance = 10
SoundEffect.Volume = Footsteps.Volume[material] or .5
SoundEffect.Parent = foot
SoundEffect:Play()
task.spawn(function()
SoundEffect.Ended:Wait()
SoundEffect:Destroy()
end)
end
I finally find it out I just need to preload all the sounds instead of loading them at execution time.
I’ll post the script here when as soon as I finished it
function Footsteps:PlayFootstepSound(foot: Instance, material: string)
if not foot then return end
local sounds = FootstepSoundsFolder:FindFirstChild(material)
if not sounds then return end
local Sound = sounds:FindFirstChild(Random.new():NextInteger(1, #sounds:GetChildren())):Clone()
if not Sound or Sound == lastFootstepSound then
Footsteps:PlayFootstepSound(foot, material)
return
end
lastFootstepSound = Sound
Sound.Parent = foot
Sound:Play()
task.spawn(function()
Sound.Ended:Wait()
Sound:Destroy()
end)
end