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

What's the problem in this script?

I have this script that makes it when a player touches the Brick with the script in it, it'll pause BackgroundMusic1 and play BackgroundMusic2... But i don't know what I'm doing wrong!

function onTouched(hit)
	if game.Workspace.BackgroundMusic1:Play() then
		game.Workspace.BackgroundMusic1:Pause()
	end
end

script.Parent.Touched:connect(onTouched)

2 comments

0

Hope you can be able to read the script :/

0

In the future, you can select the code and click the Lua symbol above the text box to apply the code formatting yourself.

1 answer

On line 2 you're calling the Play method of BGMusic1. This doesn't return anything, so the second line never runs.

Sounds have a property called IsPlaying, so your code would work like so:

function onTouched(hit)
    if game.Workspace.BackgroundMusic1.IsPlaying then
        game.Workspace.BackgroundMusic1:Pause()
    end
end

script.Parent.Touched:connect(onTouched)

However, it's not necessary to even make that check. Pausing a paused Sound does nothing at all.

There is a different check that must be made, though, to see if the Part that hit this brick belongs to a Player and isn't some debris from the workspace:

function onTouched(hit)
    if game.Players:GetPlayerFromCharacter(hit.Parent) then
	--That method call returns `nil` if a Player cannot be found for the given `hit.Parent`.
	--When hit.Parent is a Character model, it returns with that Characters' Player
	--Because a Player object is 'truthy' (that is to say, it *isn't* `false` or `nil`), the `if` check passes.
        game.Workspace.BackgroundMusic1:Pause()
    end
end

script.Parent.Touched:connect(onTouched)

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