Hi! I was trying to make it so that players touching get damaged, yet sometimes a part is in the table, so it doesn't get damaged and the script errors out. Is there something similar to pcall for this?
Script:
local parts = Range:GetTouchingParts() local Length = #parts for i = 1,Length do local attacked = parts[i] pcall(attacked.Parent.Humanoid:TakeDamage(1)) end
All help appreciated!
I believe this should work.
Instead of using a pcall
, you could try to find out if the part's Parent has a Humanoid. If it has, you then check if the Parent is the Character of a Player, just to be sure it is a Player you're dealing with. When you're sure it is a Player, you can do what you want, and make the Humanoid take damage.
local parts = Range:GetTouchingParts() local Length = #parts for i = 1,Length do local attacked = parts[i] local hum = attacked.Parent:FindFirstChild("Humanoid") if hum then local player = game.Players:GetPlayerFromCharacter(attacked.Parent) if player then hum:TakeDamage(1) end end end
If you're really persistent on using pcall
, you should know that you're using it incorrectly.
You cannot use : when trying to index a function, as this implies you are calling the function. object:Fn(...)
is the same as object.Fn(object, ...)
so in order to do the pcall correctly, youll need .
The way to achieve this is like this:
pcall(attacked.Parent.Humanoid.TakeDamage,attacked.Parent.Humanoid,1)
Lets break this down.
First, we index the function TakeDamage
by using .
which is the correct way, as mentioned above. Then, like i explained, since object:Fn(...)
is the same as object.Fn(object, ...)
, we have to pass the object to the pcall. (anything separated by commas after the 1st function will be passed to the function) Then we can pass the amount of damage to take, which in your case is 1.