How to share variables from local script to server script?

  1. What do you want to achieve? so i have a random number value in local script, and i wanted to share that value to the server script

  2. What is the issue? the shared value is nil

  3. What solutions have you tried so far? i tried to use remote event, but i think i did it wrong

local script

local part = game.Workspace.Part.ProximityPrompt

local RemoteEvent = game.ReplicatedStorage:WaitForChild("opendoor")
local CodeShare = game.ReplicatedStorage:WaitForChild("CodeShare")

local buttons = script.Parent.ButtonsBG

local input = script.Parent.InputtedCode

local codee = ""

local codeRandom = {math.random(1,9), math.random(1,9), math.random(1,9), math.random(1,9)}
for _, v in codeRandom do
	codee = codee..tostring(v)
end

CodeShare:FireServer(codee)

local currentCode = ""

input.Text = currentCode

part.Triggered:Connect(function()
	buttons.Visible = true
	input.Visible = true
end)

for i, button in pairs(buttons:GetChildren()) do

	button.MouseButton1Click:Connect(function(player)
		if tonumber(button.Name) then

			currentCode = currentCode .. button.Name
			input.Text = currentCode

		elseif button.Name == "Clear" then

			currentCode = ""
			input.Text = currentCode

		elseif button.Name == "Enter" then

			print(codee)

			if currentCode == codee then
				print("hooray!")
				currentCode = ""
				RemoteEvent:FireServer(player)

			else
				print("")
				currentCode = ""
			end


		end
	end)
	end

server script

local RemoteEvent = game.ReplicatedStorage:WaitForChild("opendoor")
local door = script.Parent
local CodeShare = game.ReplicatedStorage:WaitForChild("CodeShare")

local code


local tweenService = game:GetService("TweenService")
local tweenInfo = TweenInfo.new(
	1.5,
	Enum.EasingStyle.Quad,
	Enum.EasingDirection.Out,
	0,
	false,
	0
)
local Direc = {
	["Position"] = Vector3.new(32.5, 14.4, 4.575)
}

CodeShare.OnServerEvent:Connect(function(Player, codee)
	code = codee
end)
print(code)

RemoteEvent.OnServerEvent:Connect(function()
	local tween = tweenService:Create(door, tweenInfo, Direc)
	tween:Play()
end)



print(code)




1 Like

image
image

The issue occurs because the value is printed as nil when accessed outside the CodeShare.OnServerEvent event handler. This is because the variable code is assigned before any data is received, resulting in nil. To solve, use codee within the event handler itself or perform actions dependent on its value within that scope

1 Like