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

Script does not go into all parts?

Asked by 10 years ago

So, I have multiple parts within on model, I want to make a script that says that if ANY of those parts gets hits, then do a given function. I figured the best was to reduce lag is to have one script that says if any of these parts in the model gets hit, then do so rather then having a script in every part.

If I were to put the script into every part it would appear like this [Works]:

function onTouch(hit)
local human = hit.Parent:findFirstChild("Humanoid")
    if (human ~= nil) then
        while (human ~= nil) do
        local s = wait(1)
        local health = human.Health
        if health > 0 and health < human.MaxHealth then
            local newHealthDelta = 0.01 * s * human.MaxHealth
            health = health + newHealthDelta
            human.Health = math.min(health,human.MaxHealth)
        end
        end
            if human.Health > human.MaxHealth then
        human.Health = human.MaxHealth
    end
    end
end

connection = script.Parent.Touched:connect(onTouch)

However, in my attempt to make it work by just putting one script in the model that access all parts, I think I am doing something wrong...

script.Parent:GetChildren()
function onTouch(hit)
local human = hit.Parent:findFirstChild("Humanoid")
    if (human ~= nil) then
        while (human ~= nil) do
        local s = wait(1)
        local health = human.Health
        if health > 0 and health < human.MaxHealth then
            local newHealthDelta = 0.01 * s * human.MaxHealth
            health = health + newHealthDelta
            human.Health = math.min(health,human.MaxHealth)
        end
        end
            if human.Health > human.MaxHealth then
        human.Health = human.MaxHealth
    end
    end
end

connection = script.Parent:GetChildren().Touched:connect(onTouch)

Can someone help me with what I am doing wrong please? I think I learned how to do this wrong seeing how I taught myself...

1 answer

Log in to vote
0
Answered by
Tesouro 407 Moderation Voter
10 years ago

You have to use GetChildren in a loop. Replace the last line:

for i, child in pairs (script.Parent:GetChildren()) do
    if child:IsA("BasePart") then -- consider only the Parts of the model
        connection = child.Touched:connect(onTouch)
    end
end

Also, I don't think you need to create a connection in there if you are not using it, so just put:

child.Touched:connect(onTouch)
0
Ah I see. Thanks! PropheticExtinction 75 — 10y
0
Yowelcome. Tesouro 407 — 10y
Ad

Answer this question