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

Music name change not working?

There is an Instance of Sound in the player and I want to change the name of the SoundId.

Here is the script for the new Instance for the new player.

function onPlayerEntered(newPlayer)
	wait(5)	
	local s = Instance.new("Sound", newPlayer)
	s.Name = "Music"
print("1")	
	s:Play()
print("2")	
	s.SoundId = "http://www.roblox.com/asset/?id=142896835"
	s.Volume = 0.7
	s.Looped = true
	print("3")
end

game.Players.ChildAdded:connect(onPlayerEntered)

I want the SoundId to change when the player touches a brick, but it doesn't seem to work.

function onTouch(hit) 
	print("4")
	local s = hit.Parent:findFirstChild("Music")
	print("5")
	s.SoundId = "http://www.roblox.com/asset/?id=175664876"
end

script.Parent.Touched:connect(onTouch)

It returns this; * Workspace.MusicChaingeBrick.SoundScript:5: attempt to index local 's' (a nil value)*; when the code reaches the change of the SoundId.

1 answer

✓ Accepted answer

Well, first of all.. to hear the music you'd want to parent the Sound into the newPlayer's PlayerGui. Secondly, a Touched event returns the part that touched. You have to get the player then index the music, rather than just indexing the part that touched:

game.Players.ChildAdded:connect(function(newPlayer)
	wait(5) 
	local s = Instance.new("Sound", newPlayer.PlayerGui)
	s.Name = "Music"
	print("1")  
	s:Play()
	print("2")  
	s.SoundId = "http://www.roblox.com/asset/?id=142896835"
	s.Volume = 0.7
	s.Looped = true
	print("3")
end)
script.Parent.Touched:connect(function(hit)
	local plr = game.Players:GetPlayerFromCharacter(hit.Parent) --get the player
	if plr then --check if plr is nil
    		local s = plr.PlayerGui:FindFirstChild("Music")
    		print("5")
    		s.SoundId = "http://www.roblox.com/asset/?id=175664876"
	end
end)

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