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

How do I make a part only touch once a humanoid?

Asked by 1 year ago

So I've made a bullet, that deals damage, but I've noticed that it kills the humaoid (zombies) instantly. What do I want to achieve: -When the bullet touches a humanoid it only damages it once. -And don't delete the bullet, when it touches a humanoid, so once bullet can touch more humanoids. my script:

local bullet = script.Parent
local function onTouch(partOther)
    local humanOther = partOther.Parent:FindFirstChild("Humanoid")

    if not humanOther then return end
    if humanOther.Parent == bullet then return end
    if game.Players:GetPlayerFromCharacter(partOther.Parent) then return end

    humanOther:TakeDamage(25)
end

script.Parent.Touched:Connect(onTouch)

Thanks for reading!

1 answer

Log in to vote
1
Answered by 1 year ago
Edited 1 year ago

The .Touched event fires multiple times when it touches a single object, so it run the onTouch event multiple times and subsequently damage the zombie multiple times, killing it.

This can be fixed by storing a list of all zombies damaged, so that we can check if we have already damaged said zombie or not.

local damaged = {}

local function onTouch(partOther)

    local humanOther = partOther.Parent:FindFirstChild("Humanoid")

    if not humanOther then return end
    if humanOther.Parent == bullet then return end
    if game.Players:GetPlayerFromCharacter(partOther.Parent) then return end

    if table.find(damaged, humanOther) then return end

    table.insert(damaged, humanOther)

    humanOther:TakeDamage(25)

end
0
Thanks for you reply, but now it says "Workspace.Bullet.BulletDamageScript:15: attempt to call a nil value " line 15 is "table.add(damaged, humanOther)", how can I fix this? Kisferenc 47 — 1y
0
oopsies its table.insert(damaged, humanOther) sorry virushunter9 943 — 1y
0
Yep, it's working! Thank you! Kisferenc 47 — 1y
0
Yep, it's working! Thank you! Kisferenc 47 — 1y
Ad

Answer this question