I am trying to track down (and it has been 2 years so learning all of this again) what I need to do to fix this script (I bet more are like this one).
local wspace = game.Workspace local rumble = wspace.RumbleSoundPart local magnitude = 0 local temp = 0 local temp2 = 0 local maxdistance = 18 while true do wait(0.5) for i,v in pairs(game.Players:GetChildren()) do magnitude = ((v.Character.Head.Position - wspace.RumbleSoundPart.Position).magnitude) - 4 if magnitude < 1 then magnitude = 1 end temp = (magnitude/maxdistance) if temp > 0.4 then temp = 0.4 end temp2 = 1 - temp if temp2 > 0.4 then temp2 = 0.4 end if temp2 < 0 then temp2 = 0 end wspace.MusicScript.Sound.Volume = temp wspace.MusicScript.Sound1.Volume = temp wspace.MusicScript.Sound2.Volume = temp wspace.RumbleSoundPart.Sound.Volume = temp2 end end
Error is Attempt to index field 'Character' (a nil value). What should I add to make sure the character is in the game before this gets called? I tried a few things but nothing seemed to work.
Use the CharacterAdded event of a player to get a reference to their character when it's replicated.
ex:
game.Players.PlayerAdded:Connect(function(player) player.CharacterAdded:Connect(function(character) -- Character is returned from the CharacterAdded event so you can just include it in the callback function as a parameter end) end)
local wspace = game.Workspace local rumble = wspace.RumbleSoundPart local magnitude = 0 local temp = 0 local temp2 = 0 local maxdistance = 18 while wait(0.5) do for i,v in pairs(game.Players:GetChildren()) do if not v.Character then repeat wait() until v.Character end v.Character:WaitForChild("Head") magnitude = ((v.Character.Head.Position - wspace.RumbleSoundPart.Position).magnitude) - 4 if magnitude < 1 then magnitude = 1 end temp = (magnitude/maxdistance) if temp > 0.4 then temp = 0.4 end temp2 = 1 - temp if temp2 > 0.4 then temp2 = 0.4 end if temp2 < 0 then temp2 = 0 end wspace.MusicScript.Sound.Volume = temp wspace.MusicScript.Sound1.Volume = temp wspace.MusicScript.Sound2.Volume = temp wspace.RumbleSoundPart.Sound.Volume = temp2 --sf=string.format --print(sf("temp is %f, temp2 is %f, magnitude is %f",temp, temp2, magnitude)) end end
To wait for the character, you first have to make sure that the character isn't nil, and if it is, wait for it using a repeat-until loop. After that, you want to wait for all parts of the character to be added, hence the Character:WaitForChild("Head").