Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Is there something similar to pcall() in this situation?

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!

4 comments

1

Could you please include the whole script or most of it as this is hard to understand

0

done

0

I don't really understand what the problem is. Do you mean that sometimes, it isn't a character that touches Range, but another part?

0

exactly, sorry for no clarification before xd

2 answers

✓ Accepted answer

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.

This discussion is preserved as it was. New answers, comments, and votes are closed.