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
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)
You put Sound.SoundId = math.random[#Sounds]
this makes no sense if you're trying to get the sound id from the table.
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