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

Why is this for loop doing this?

Asked by 9 years ago

I have a script that fires when a player steps on a part. The script is supposed to make the player invisible, but in a manner so that the player slowly gets more and more transparent. Here's the script: (note: I got rid of the non-important parts of the script)

local limbs = get.Parent:GetChildren() -- get is the argument for the Touched function in the script
for i = 1, #limbs do
    if limbs[i].ClassName == "Part" then
        repeat
        wait()
        limbs[i].Transparency = limbs[i].Transparency + 0.1
        until
        limbs[i].Transparency >= 1
        limbs[i].Transparency = 1
    end
end

Instead of decreasing all of the parts' transparency, it only decreases them one by one (i.e. the script will slowly turn 1 part transparent and that part only, and then move onto the next part until all parts are transparent). Why is this happening, and how can I fix it?

2 answers

Log in to vote
0
Answered by
adark 5487 Badge of Merit Moderation Voter Community Moderator
9 years ago

local limbs = get.Parent:GetChildren() -- get is the argument for the Touched function in the script for i = 1, #limbs do if limbs[i].ClassName == "Part" then repeat wait() limbs[i].Transparency = limbs[i].Transparency + 0.1 until limbs[i].Transparency >= 1 limbs[i].Transparency = 1 end end

The problem is that you are iterating over each part individually in the inner loop. You have to change them all at once, then wait(). A good way to do this is to use a numeric for loop as the outer loop, to hold the 'current' Transparency. Additionally, you should use the IsA method instead of directly reading the ClassName property.

(P.S. You can use a generic for here to save some writing):

local limbs = get.Parent:GetChildren()

for i = 0, 1, .1 do
    for _, limb in ipairs(limbs) do
        if limb:IsA("BasePart") then --Parts, WedgeParts, Trusses -- This is why you use IsA
            limb.Transparency = i
        end
    end
    wait() --This entire loop will only take about .3 seconds to make the Player transparent. I suggest making the 'step' part of the loop smaller to slow it down.
end

for _, limb in ipairs(limbs) do
    if limb:IsA("BasePart") then --Parts, WedgeParts, Trusses -- This is why you use IsA
        limb.Transparency = 1
    end
end
Ad
Log in to vote
-1
Answered by
Hexcede 52
9 years ago

The wait is whats causing the problem. I don't know how to solve it unless you want to create a separate script for every part.

Answer this question