I have a script that teleport player back to spawn (using loadcharacter) and reward 100 cash when a player touch a part This is my script:
local Debounce = false script.Parent.Touched:connect(function(hit) if Debounce == false then Debounce = true if hit.Parent.Humanoid ~=nil then print("touched") local player = game.Players:GetPlayerFromCharacter(hit.Parent) player.leaderstats.Cash.Value = player.leaderstats.Cash.Value + 100 player:LoadCharacter() workspace.MapChanger.Waittime.Value = workspace.MapChanger.Waittime.Value /2 wait(5) Debounce = false end end end)
sometime when a player touch it, it give me an error saying Humanoid is not a valid player of Accessory then the script stop working... How can i prevent that?
Sorry for my bad english :(
To make script skip error and keep working, we use pcall()
. For example:
local Succeed, ErrorMessage = pcall(function() write("I'm running in pcall() :D") --this will return error because the function have to be print() not write() end) if Succeed then print("Nothing wrong :D") else print("It error :(", ErrorMessage) end
Succeed
is a boolean
value, if there is no error, it will return true
or it will return false
if there is error. ErrorMessage
is the error message(duh...) that the script return if there is any error.
pcall()
is only use for can't handle error like Http request error, Gamepass purchase,... but that is another thing.
Using pcall()
too much is not a good habit, it better to fix the error by your self than skip it.
For more information about pcall()
, click here.
*Note: I don't have the link to pcall()
document so... Find it your self :)
Hello. First, i will teach you how to check if something exists.
local hum = hit.Parent:FindFirstChild("Humanoid") --If it finds the humanoid, returns the humanoid, if it doesnt, returns nil if hum then Hum exists! end
Now, pcalls.
local worked, errormessage = pcall(function() --pcalls are functions that returns if it worked and the error message. pppprint() end) if worked == false then print(errormessage) --would print that pppprint() isnt a existant function or something. yeah. end
Hope that helped!