Does anyone know how I can turn the following code from a client side script to a server side script?
script.Parent.Activated:Connect(function()
local Backpack = game.Players.LocalPlayer.Backpack
local tool = game.ReplicatedStorage.Wand
print(Backpack)
Backpack:FindFirstChild("Wood")
if Backpack:FindFirstChild("Wood") and Backpack:FindFirstChild("Tea") then
local WandClone = tool:Clone()
WandClone.Parent = Backpack
Backpack:FindFirstChild("Wood"):Destroy()
Backpack:FindFirstChild("Tea"):Destroy()
end
end)
It’s pretty much there already, just change LocalPlayer to :GetPlayerFromCharacter and change the LocalScript to a Script.
Code:
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Tool = script.Parent
Tool.Activated:Connect(function()
local Character = Tool.Parent
local player = Players:GetPlayerFromCharacter(Character)
if not player then
return
end
local Backpack = player.Backpack
local tool = ReplicatedStorage.Wand
if Backpack:FindFirstChild("Wood") and Backpack:FindFirstChild("Tea") then
Backpack.Wood:Destroy()
Backpack.Tea:Destroy()
local WandClone = tool:Clone()
WandClone.Parent = Backpack
end
end)
I added more variables for readability, only thing that really changed was Players.LocalPlayer.
Create a RemoteEvent in ReplicatedStorage named, like, “GiveWandTool” or something.
Create a new server script in ServerScriptService named anything, it doesn’t matter.
Write this in the LocalScript you provided (replace the old code with this):
script.Parent.Activated:Connect(function()
game.ReplicatedStorage.GiveWandTool:FireServer() -- Replace GiveWandTool with whatever you named the event
end)
Write this in the server script we just created:
game.ReplicatedStorage.GiveWandTool.OnServerEvent:Connect(function(player)
local Backpack = player.Backpack
local tool = game.ReplicatedStorage.Wand
print(Backpack)
Backpack:FindFirstChild("Wood")
if Backpack:FindFirstChild("Wood") and Backpack:FindFirstChild("Tea") then
local WandClone = tool:Clone()
WandClone.Parent = Backpack
Backpack:FindFirstChild("Wood"):Destroy()
Backpack:FindFirstChild("Tea"):Destroy()
end
end)
Explanation if you didn't understand
A RemoteEvent is an event you can use to communicate between the client and server. It can fire and be received both ways.
One important thing to mention is that when using .OnServerEvent, the first parameter passed will always be the player that fired the event.
In the code we just wrote, we fired the RemoteEvent we created on the client when the player activates the button/tool/whatever, so that the server could receive the event and do the action, which is give the player the wand.