The sounds of my game only play about once in three

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 dont have any ideas why this append :confused:

https://youtu.be/ail7VGJ1J98

2 Likes

I figured out that if it’s always the same sound it kinda works but I want to change randomly sounds :confused:

Just changed these lignes

local soundId = sounds[1]
	
-- if not soundId or soundId == lastFootstepSound then
--	Footsteps:PlayFootstepSound(foot, material)
--	return
-- end
1 Like

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 :confused:

Here’s the isLoaded state of each songs:
Console

It took me some time but finally I created all the sounds needed in the replicated storage

And in my code I just clone them using this code:

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

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.