Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How do I make this model make a sound upon touched?

I am making diamonds to collect on my map! They regen and give points perfectly, but they do not make a sound when collected. When I try to put in a sound, the script breaks! I also noticed other scripts will have the sound looping so if they stay in the spot where it regenerates, it plays the sound constantly.

I would like it to play the sound only when the item is not transparent. That, or only allow the sound to function every 7 seconds (the time it regens) whatever is easier :)

Here is my script without trying to add in any sounds -

(Please let me know what and where I need to put it! Thank you so much I appreciate it a ton!)

waittime = 7 -- Time Between each hit
amnt = 10 --how much you get for it
function onTouched(part)
	local h = part.Parent:findFirstChild("Humanoid")
	if (h~=nil) then
		local thisplr = game.Players:findFirstChild(h.Parent.Name)
		if (thisplr~=nil) then
			local stats = thisplr:findFirstChild("leaderstats")
			if (stats~=nil) then
				local score = stats:findFirstChild("Money")
				if (score~=nil) then
					score.Value = score.Value + amnt

				end
			end
		end
		
		script.Parent.Transparency = 1
		script.Disabled = true
		wait(waittime)
		script.Parent.Transparency = 0
		script.Disabled = false		


	end
end

script.Parent.Touched:connect(onTouched)

2 answers

✓ Accepted answer

What you need

You need to reference your sound object, then simply use the Play function when the Touched event fires.


Notes

  • Establish a debounce to prevent repeating sounds.

  • Set the 'Looped' property of the sound object to false if you still find your sound repeating.

  • The GetPlayerFromCharacter function can be used here to retrieve the player easily


Code

local sound = script.Parent:FindFirstChild("Sound") --This is your sound
local waittime = 7 -- Time Between each hit
local amnt = 10 --how much you get for it
local db = false --the debounce

function onTouched(part)
	if not db then
		db = true --Turn on debounce
		local thisplr = game.Players:GetPlayerFromCharacter(part.Parent)
		if thisplr then
			local stats = thisplr:FindFirstChild("leaderstats")
			if stats then
				local score = stats:FindFirstChild("Money")
				if score then
					score.Value = score.Value + amnt
					sound:Play(); --Play the sound
				end
			end
		end
		script.Parent.Transparency = 1
		wait(waittime)
		script.Parent.Transparency = 0 
		db = false --Turn off debounce
	end
end

script.Parent.Touched:connect(onTouched)

1 comment

0

It worked, thank you so much! You are amazing! Thank you for explaining to me how it works as well!

This discussion is preserved as it was. New answers, comments, and votes are closed.