Transferring variable from local script to script

I am trying to transfer a variable from a local script to a script. I am using for i, v in pairs and remote events but I am having trouble transferring the “v” to a server script.

script.Parent.MouseButton1Down:Connect(function()
	 for i, v in pairs(game.Workspace:GetChildren()) do
		if v.Name == script.Parent.Parent.RedText.Text then
			if v:FindFirstChild("Humanoid") then
				game.ReplicatedStorage.Red:FireServer()
				print("Fired!!!")
			end
		end
	end
end)

Sorry if this has some bad grammar in it! I was in a rush.

1 Like
script.Parent.MouseButton1Down:Connect(function()
	for i, v in pairs(game.Workspace:GetChildren()) do
		if v.Name == script.Parent.Parent.RedText.Text then
			if v:FindFirstChild("Humanoid") then
				game.ReplicatedStorage.Red:FireServer(v)
				print("Fired!!!")
			end
		end
	end
end)

You can just pass the variable “v” as an argument to FireServer().

Then in the script containing “OnServerEvent” just do:

game.ReplicatedStorage.Red.OnServerEvent:Connect(function(player, v)
	--do stuff with player and v
end))

When I use “v” it gives me an error.
Code -

v.Torso.BrickColor = BrickColor.new("Really red")

Error -
ServerScriptService.Red:2: attempt to index nil with ‘Torso’

What is your complete script? Both if possible.

Local Script -

script.Parent.MouseButton1Down:Connect(function()
	 for i, v in pairs(game.Workspace:GetChildren()) do
		if v.Name == script.Parent.Parent.RedText.Text then
			if v:FindFirstChild("Humanoid") then
				game.ReplicatedStorage.Red:FireServer()
				print("Fired!!!")
			end
		end
	end
end)

Script -

game.ReplicatedStorage.Red.OnServerEvent:Connect(function(player, v)
	v.Torso.BrickColor = BrickColor.new("Really red")
end)

This is erroring because you simply didn’t pass v as an argument. You can easily fix this by doing this:

game.ReplicatedStorage.Red:FireServer(v) --Passes v to server

Sidenote: It’s possible to do this:

--Local script
game.ReplicatedStorage.Red:FireServer(v) --Passes v to server

--Server script
game.ReplicatedStorage.Red.OnServerEvent:Connect(function(player, e) --e is still v, we just named the variable differently!
   e.Torso.BrickColor = BrickColor.new("Really red")
end)

As I point out @Limited_Unique, you need to pass the variable through the LocalScript

script.Parent.MouseButton1Down:Connect(function()
	for i, v in pairs(workspace:GetChildren()) do
		if v.Name == script.Parent.Parent.RedText.Text then
			if v:FindFirstChild("Humanoid") then
				game:GetService("ReplicatedStorage").Red:FireServer(v)
				print("Fired!!!")
			end
		end
	end
end)

and on the server you can verify that it is correct

game:GetService("ReplicatedStorage").Red.OnServerEvent:Connect(function(player, v)
	if v and v:FindFirstChild("Torso") then
		v.Torso.BrickColor = BrickColor.new("Really red")
	end
end)
2 Likes