When trying to write a script for when a player touches a part it kills them and rewards with 1 win. I have gotten the kill part to work but not to win. The script is a server script. I have got this error too:
19:23:10.736 Workspace.FlagQuiz.Done.Part.KillScript:8: attempt to perform arithmetic (add) on Instance and number - Server - KillScript:8
Script:
local Kill = script.Parent
game.Players.PlayerAdded:Connect(function(plr)
local wins = plr.leaderstats.Wins
Kill.Touched:Connect(function(hit)
if hit.Parent:FindFirstChild("Humanoid") then
hit.Parent.Humanoid.Health = 0
wins = wins + 1
end
end)
end)
That’s the fix, but I recomend also moving this event outside of the playeradded event, this would probably be more beneficial on resources and also look cleaner, not sure why you put it in a playeradded event.
And again, I recommend moving that .Touched event outside of the playeradded event. This current code would lead to memory leaks which would overall impact the player’s experience.
Yes i am learning coding but i have a problem with the script. When I have reloaded and aren’t touching the part it still says that I am getting an extra 24 - 30 wins when i die instead of 1
Script:
local Kill = script.Parent
game.Players.PlayerAdded:Connect(function(plr)
local wins = plr:WaitForChild("leaderstats").Wins
Kill.Touched:Connect(function(hit)
if hit.Parent:FindFirstChild("Humanoid") then
hit.Parent.Humanoid.Health = 0
wait(3)
wins.Value = wins.Value + 1
wait(10)
end
end)
end)
I recommend you learn about debouncing, debouncing are boolean variables that are used for cooldowns like this. When you want an event to run a certain amount of times or what not.
Change this to a local script and store it in starterplayerscripts. And add a remote event into replicatedstorage.
-- Local script
local RepStorage = game:GetService("ReplicatedStorage")
local RE = Repstorage:WaitForChild("RemoteEvent")
local Kill = workspace:WaitForChild("Kill")
local db = false
Kill.Touched:Connect(function(hit)
if hit.Parent:FindFirstChild("Humanoid") then
if db == false then
db = true
RE:FireServer(hit)
task.wait(3)
RE:FireServer()
task.wait(10)
db = false
end
RE.OnServerEvent:Connect(function(player, hit)
if hit then
hit.Parent.Humanoid.Health = 0
else
local wins = player.leaderstats.Wins
wins.Value += 1
end
I’m in a bit of a hurry so I can’t write the best most secure code but for now this would be good
But if you’re still learning how to use events, functions, printing, variables, etc. I recommend going back a bit before attempting harder stuff like this. These are more advanced fundamentals that you should know after learning the basics of luau.
Also copy and paste the code again because I just edited it. I’ll give you some better code for this later on, using attributes from the server and what not. (I’ll explain that after).