Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

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

Asked by 4 years ago
Edited 4 years ago

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!

1
Could you please include the whole script or most of it as this is hard to understand Spjureeedd 385 — 4y
0
done ScriptingNubs 55 — 4y
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? Spjureeedd 385 — 4y
0
exactly, sorry for no clarification before xd ScriptingNubs 55 — 4y

2 answers

Log in to vote
1
Answered by 4 years ago

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
Ad
Log in to vote
4
Answered by
ArtBlart 533 Moderation Voter
4 years ago

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.

Answer this question