Attempt to index nil with "Touched"

I’m trying to make a script that will play different audios when you touch certain parts. It worked just yesterday, but now it does not. Here is the error:

Players.doctorpepper126.PlayerScripts.MusicPlayer.Audio1:3: attempt to index nil with ‘Touched’

Here is the script:

local cld = false script.object.Value.Touched:Connect(function(hit) local player = game.Players:GetPlayerFromCharacter(hit.Parent) if (player ~= nil) then if cld == false then cld = true workspace.audio.SoundId = script.id.Value wait(1) cld = false end end end)
Any help would be appreciated

2 Likes

What is the value assigned to script.object.Value property?

2 Likes

A part in the Workspace called “MusicPart1”

Is it anchored? Maybe if it’s non-collideable it might be falling of the world, thus destroying it.

No, but I looked again and now it seems it is clearing the value when I click play.

local cld = false
script.object.Value.Touched:Connect(function(hit)
local player = game.Players:GetPlayerFromCharacter(hit.Parent) 
if (player ~= nil) then 
      if cld == false then
         cld = true 
         workspace.audio.SoundId = script.id.Value 
         wait(1) 
         cld = false 
       end 
end
end)

just bc i want ppl to be able to read :slight_smile:

2 Likes

instead of

script.object.Value.Touched:Connect(function(hit)

maybe try

local object = script:WaitForChild("object")
local Value = object:WaitForChild("Value")
Value.Touched:Connect(function(hit)

and just a side note:
Try checking if
A. Hit does not equal to nil
B. If a humanoid exists in the Hit.Parent

local cld = false
script.object.Value.Touched:Connect(function(hit)
if hit == nil then return end -- Ends the script if it equals to nil [nothing]
if not hit.Parent:FindFirstChildWhichIsA("Humanoid") then return end
local player = game.Players:GetPlayerFromCharacter(hit.Parent) 
if (player ~= nil) then 
      if cld == false then
         cld = true 
         workspace.audio.SoundId = script.id.Value 
         wait(1) 
         cld = false 
       end 
end

Thanks @cureog :happy2:
I get errors if :GetPlayerFromCharacter(character.Parent) is not an actual player!
Hope this helped! Thank you for reading! - Sincerely, @oscoolerreborn

just a side note, its wierd namin a block ‘value’
:thinking:

3 Likes