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

How To Make A GUI Button Change Character CFrame?

How do I make a gui button teleport the player to a certain CFrame?

1 comment

0

Not a request site

3 answers

✓ Accepted answer

You will need to use MouseButton1Click. This fires when a TextButton is pressed.

TextButton.MouseButton1Click:Connect(function()
	workspace[game.Players.LocalPlayer.Name].HumanoidRootPart.CFrame = CFrame.new(CFRAME)
end)

2 comments

0

Why would you reference the character like that lmao

0

I would recommend using player.character instead of [game.Players.LocalPlayer.Name]

But this in a local script attached to the button:

local CFRAME = CFrame.new() -- Change to whatever you want


local button = script.Parent

local player = game:GetService('Players').LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()

button.MouseButton1Click:Connect(function()
	character:SetPrimaryPartCFrame(CFRAME)
end)

In Roblox, there are two sides. The first side is the CLIENT side, where everything in that side is LOCAL (works for each player, separately) like the PlayerGui. The other side is the SERVER side, where everything on that side works for all the server like the Workspace. Roblox made that system to prevent hacks.

The MouseButton1Click function is fired when a player clicks a TextButton. However, it will only fire for the player separately (LOCAL SIDE). So the script that runs this function must be a LOCALSCRIPT, because the TextButton is placed in a PlayerGui (The PlayerGui on the local side) Also, everything in the workspace is on the SERVER side, so the localscript cannot change the player's character's CFrame.

So how can we do that?

Remote events let script and localscripts send signals between themselves. What we will do is to send a signal when the player clicks the button, from a localscript to a script by a remote event.

First, insert a remote event named "Teleport" in the ReplicatedStorage.

Next, insert a localscript in the TextButton you want the player to click and copy and paste this in the localscript:

script.Parent.MouseButton1Click:Connect(function()
	game.ReplicatedStorage.Teleport:FireServer() -- sends the signal
end)

Now, insert a normal script in the ServerScriptService and copy and paste this in the script:

game.ReplicatedStorage.Teleport.OnServerEvent(player) -- get the signal
	local TeleportPosition = WRITE THE POSITION YOU WANT THE PLAYER TO 
BE TELEPORTED
	game.Workspace:WaitForChild(player.Name).HumanoidRootPart.CFrame = CFrame.new(TeleportPosition)
end)

I chose the ReplicatedStorage to insert the Remote Event, because both scripts and localscripts can access to it (the ReplicatedStorage is both SERVER side and LOCAL side).

Hope this helped!

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