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

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

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

✓ Accepted answer

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.

4 comments

0

Thanks so much!

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)

0

Sounds like your script isn't local.

0

Oh i need to make a local? Whoops sorry.

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