Going to start with the problem so here it is:
I have two players on the server. Player1 and Player2. When Player1 touches the part then LocalScript in the StarterPlayerScripts find who touched and invokes server with data.
LocalScript:
game.Workspace.Part.Touched:Connect(function(hit)
local player = game.Players:GetPlayerFromCharacter(hit.Parent)
if player then
print(player)
game.ReplicatedStorage.RemoteFunction:InvokeServer(1)
end
end)
Output is working well, its printing the name who had touched the part.
Then we go in the ServerScriptService into Script:
game.ReplicatedStorage.RemoteFunction.OnServerInvoke = function(player, amount)
print(player, amount)
end
And here is the problem(my best guess) because its prints both players(Player1 and Player2) and if I wanna to give a reward to a player who had touched the part it will give a reward to the all players in the game.
Here is the all output’s if Player2 touched a part:
Player2 1 - Server - Script:2
Player1 1 - Server - Script:2
Now will ask my questions:
Is it okay that its printing in the Player1’s output that Player2 had touched a part? Or it should write it only in the player’s output that had touched a part?
Why its working this way and it invokes for both Player’s in the Server-side?
Is there a way to fix that or I should use something else to do it?
Thanks to everyone who took the time to read this and help out with this problem. I really appreciate your input
Well, first, this is an extremely exploitable system, so I would not advise using the same practices. The reason is that the LocalScript is running for everyone, so even if one person touches it, everyone gets it because its only checking if it’s a player that touched it, but it isn’t checking if that player is the LocalPlayer.
To fix it, all you would have to do is:
game.Workspace.Part.Touched:Connect(function(hit)
local player = game.Players:GetPlayerFromCharacter(hit.Parent)
if player and player == game:GetService("Players").LocalPlayer then
print(player)
game.ReplicatedStorage.RemoteFunction:InvokeServer(1)
end
end)
But, as I said, this is extremely exploitable, as someone can just do game.ReplicatedStorage.RemoteFunction:InvokeServer(1000000000000000) from their executors. I suggest just running your Touched event on the server and just adding the amount directly from the player variable.
game.Workspace.Part.Touched:Connect(function(hit)
local player = game.Players:GetPlayerFromCharacter(hit.Parent)
if player then
-- Do your reward here
end
end)
To add a cash value, you could just add a NumberValue to the part and retrieve it or you could add an attribute. Alternatively you can just specify it in your code by hardcoding it. Up to you.
Ohhh so there is no need to do this from local script and then use remote events(functions)? I was sure its better vs exploiters. And now I guess its harder to exploit it if I will do this in the server side code? Btw your code is working, thanks!