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

How to access the a player's audio in gui on a touched event?

Asked by 6 years ago

So what I'm trying to do is have it to where the player touches a part, and audio will play inside of the player's gui. It all works find, but once started in player it says that line 9 is a nil value. Anyone know how to fix this?

local buttonPressed = false

function onTouch(hit)
    if not buttonPressed then
    buttonPressed = true
    if hit.Parent:FindFirstChild("Humanoid") then
        local user = game.Players:GetPlayerFromCharacter(hit.Parent)
    if user then
            local startui = user:FindFirstChild("PlayerGui")
      if startui then
                startui.StartRace:Play()
      end
    end
end

    buttonPressed = false

    end
end

script.Parent.Touched:connect(onTouch)

1 answer

Log in to vote
1
Answered by
Goulstem 8144 Badge of Merit Moderation Voter Administrator Community Moderator
6 years ago
Edited 6 years ago

You need to do this from the client. Put a LocalScript in StarterGui, put the StartRace Sound object in the LocalScript.

Get the character object from the LocalPlayer, and check if the object that touched the part is a descendant of it. This will tell you if the character touched it.

local plr = game.Players.LocalPlayer --The Player
local char = plr.Character or plr.CharacterAdded:Wait() --Character
local audio = script:WaitForChild("StartRace") --Audio
local buttonPressed = false

function onTouch(hit)
    if not buttonPressed then
        buttonPressed = true
        if hit:IsDescendantOf(char) then --If character touched
            audio:Play() --Play audio
        end
        buttonPressed = false;
    end
end

--Below is object to touch.
workspace.StartRace.Touched:Connect(onTouch) --`connect` is deprecated
Ad

Answer this question