Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

What's the problem in this script?

Asked by 9 years ago

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)
0
Hope you can be able to read the script :/ DrTacoaX -5 — 9y
0
In the future, you can select the code and click the Lua symbol above the text box to apply the code formatting yourself. adark 5487 — 9y

1 answer

Log in to vote
2
Answered by
adark 5487 Badge of Merit Moderation Voter Community Moderator
9 years ago

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)
Ad

Answer this question