Players:GetPlayers() not getting variable

  1. What do you want to achieve? I want to achieve a system that allows me to give coins to players if I type in their username.

  2. What is the issue? Include screenshots / videos if possible! The issue is that it never gives them the coins. It would always print not a valid player. I am 100% sure I spelled my username correctly. I can’t include screenshots or videos.

  3. What solutions have you tried so far? Did you look for solutions on the Developer Hub? I have looked for many solutions on the Developer Hub and Youtube and none really matched what I was trying to achieve.

Local Script (inside UI)

local givenplr = nil
local amount = nil

game.ReplicatedStorage.GiveCoins.OnClientEvent:Connect(function(player)
	script.Parent.Parent.Parent.Frame.Visible = true
end)

script.Parent.MouseButton1Click:Connect(function()
	givenplr = script.Parent.Parent.NameBox.Text
	amount = script.Parent.Parent.AmountBox.Text
	script.Parent.Parent.NameBox.Text = ""
	script.Parent.Parent.AmountBox.Text = ""
	game.ReplicatedStorage.AddCoins:FireServer(givenplr, amount)
	print("Fired!")
end)

game.ReplicatedStorage.Cleanup.OnClientEvent:Connect(function(player)
	givenplr = nil
	amount = nil
	script.Parent.Parent.Parent.Frame.Visible = false
end)

Script (inside ServerScriptService)

game.ReplicatedStorage.AddCoins.OnServerEvent:Connect(function(givenplr, amount)
		local Players = game:GetService("Players")

		for i, player in pairs(Players:GetPlayers()) do
			print("Done!")
			if player.Name == givenplr then
				player.Amount.Value = amount
				player.leaderstats.Coins.Value = player.leaderstats.Coins.Value + player.Amount.Value
				player.Amount.Value = 0
				game.ReplicatedStorage.Cleanup:FireClient(player)
				print("Done!")
			else
				print("Not a valid player!")
			end
		end
	end)

On the server when a remote event is fired by a client the first variable will ALWAYS be the player with the client that fired the RemoteEvent

i would recommend changing this

game.ReplicatedStorage.AddCoins.OnServerEvent:Connect(function(givenplr, amount)

to

game.ReplicatedStorage.AddCoins.OnServerEvent:Connect(function(plr,givenplr, amount)

and be careful as exploiters can easily abuse this

2 Likes

Wow, all I had to do was add a plr argument. What do you mean on how players could exploit this?

Players with exploit clients can fire remote events meaning they could give them selves free money and change this

amount = script.Parent.Parent.AmountBox.Text

to this

amount = tonumber(script.Parent.Parent.AmountBox.Text)

so it will do NumberValue + NumberValue not NumberValue + StringValue

1 Like

Wow, it works! Thank you so much!