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

Detecting Humanoid and Making a sound doesn't work?

Hello, I'm just wondering why this script won't work (A local script inside starterGui) there is no ouput by the way.

Please support me with any solutions, thanks.

local Plr = game.Players.LocalPlayer
local Char = Plr.Character
if not Char or not Char.Parent then
    Char = Plr.CharacterAdded:wait()
end

function PlaySound()
	local Sounds = {"1470936712", "1470937053", "1470937969"}
	wait()
	if Char.Humanoid.Health < 100 then
		local Sound = Instance.new('Sound')
		Sound.SoundId = math.random[#Sounds]
		Sound.Parent = Char:WaitForChild('Head')
		Sound:Play()
		wait(Sound.TimeLength)
		Sound:Destroy()
	end
end

while true do
	while Char.Humanoid.Health < Char.Humanoid.MaxHealth do
		PlaySound()
	end
	Char.Humanoid.HealthChanged:Wait()
end

1 comment

0

i think you need the rbxassetid:// prefix in the SoundId. You also need to put Sounds[math.random(#Sounds)] on line 12.

3 answers

✓ Accepted answer

So, I put your script into an empty baseplate and started making my character take damage. Unlike what you said, it did output an error about line 12:

19:19:33.619 - Players.Player1.PlayerGui.LocalScript:12: attempt to index field 'random' (a function value)

The reason for the problem that you are stumbling upon is the fact that you are using square brackets instead of round brackets for math.random. Remember that math.random is a function and not a table. Round brackets () are used to contain parameters for functions or in mathematical equations, and square brackets [] are used to identify an item in a table.

To fix line 12, simply replace the square brackets with round brackets, like so:

Sound.SoundId = math.random(#Sounds)
  1. You put Sound.SoundId = math.random[#Sounds] this makes no sense if you're trying to get the sound id from the table.

  2. Try using print functions to see where your error is.

also I suggest using a while true do if you want your sound to repeat every time the player's health goes down or something.

Trying adding a random seed Use this...

local Plr = game.Players.LocalPlayer
local Char = Plr.Character
if not Char or not Char.Parent then
    Char = Plr.CharacterAdded:wait()
end
math.randomseed(tick()) -- this is random seed

function PlaySound()
    local Sounds = {"1470936712", "1470937053", "1470937969"}
    wait()
    if Char.Humanoid.Health < 100 then
        local Sound = Instance.new('Sound')
        Sound.SoundId = math.random[#Sounds]
        Sound.Parent = Char:WaitForChild('Head')
        Sound:Play()
        wait(Sound.TimeLength)
        Sound:Destroy()
    end
end

while true do
    while Char.Humanoid.Health < Char.Humanoid.MaxHealth do
        PlaySound()
    end
    Char.Humanoid.HealthChanged:Wait()
end

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