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.
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.