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

How do you grab the character from a player who clicks a GUI button?

Asked by 4 years ago
Edited 4 years ago

Trying to make a simple game to test my coding abilities, and I've stumbled upon this problem. How would I grab the character whenever they click a TextButton inside a GUI? I don't know if this will help, but here is my code.

local button = script.Parent
local character = game.Players:GetPlayerFromCharacter(character)
button.MouseButton1Click:Connect(function()
    if game.Workspace.Sound.Playing ~= true then
        character.Humanoid.WalkSpeed = 90
        game.Workspace.Sound.Playing = true
        game.Workspace.Sound.Looped = true
    else
        character.Humanoid.WalkSpeed = 16
        game.Workspace.Sound.Playing = false
        game.Workspace.Sound.Looped = false
    end
end)

I removed a couple of things so right now it isn't finished.

1 answer

Log in to vote
0
Answered by 4 years ago

Just use the LocalPlayer property of Players, it points to the player the local script is running on, and is nil to the server. From the player, you can get their character via the Character property which points to the character model in workspace.


Also, the proper way to play a sound is sound:Play(), not sound.Playing = true.

local button = script.Parent
local client = game:GetService("Players").LocalPlayer
local character = client.Character or client.CharacterAdded:Wait()
-- character may not be loaded yet. so we wait if it isn't
local sound = game:GetService("Workspace").Sound

button.Activated:Connect(function()
    if not sound.IsPlaying then -- no need for ~= true or == true etc 
        character.Humanoid.WalkSpeed = 90
        sound:Play()
        sound.Looped = true
    else
        character.Humanoid.WalkSpeed = 16
        sound:Stop() -- proper way to stop is with the :Stop method
        sound.Looped = false
    end
end)

Look at how cleaner it is. Use variables to avoid repetition.

0
Thanks so much! Just_Moop 27 — 4y
0
Just tried this, and it returned this error:Players. Just_Moop.PlayerGui.Run.Frame.TextButton.Script:3: attempt to index local 'client' (a nil value) Just_Moop 27 — 4y
0
Sounds like your script isn't local. DeceptiveCaster 3761 — 4y
0
Oh i need to make a local? Whoops sorry. Just_Moop 27 — 4y
Ad

Answer this question