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

Code works but wondering if there is a better way? Cloning a part to each character?

Asked by
FiredDusk 1466 Moderation Voter
7 years ago

This script works but is there a better/easier way of scripting this? - This script just clones a part to each character in the game and welds it to their own torso.

while wait() do
    local Part = game.ReplicatedStorage:WaitForChild('Cop')
    local plrs = game.Players:GetPlayers()
    for i = 1, #plrs do
        local Char = plrs[i].Character
        local Torso = Char.Torso

        if not Torso:FindFirstChild('Cop') then
            local clonedPart = Part:Clone()
            clonedPart.Parent = Torso

            local Weld = Instance.new('Weld', Torso)
            Weld.Part0 = Torso
            Weld.Part1 = clonedPart
            Weld.C0 = CFrame.new(0,0,0)
        end
    end
end
0
The code is fine man. Efficiency wise it can't be improved much more. I guess if anything I would suggest using a generic for to iterate through your table, rather than a numerical. But it's completely your preference and your way works just fine. Goulstem 8144 — 7y
0
Is the an example of what the for loop you are talking about looks like? FiredDusk 1466 — 7y

2 answers

Log in to vote
1
Answered by 7 years ago

Try using the PlayerAdded and CharacterAdded events:

local part = game:ReplicatedStorage:WaitForChild("Cop")

game.Players.PlayerAdded:connect(function(p)
    p.CharacterAdded:connect(function(char)
        local torso = char:WaitForChild("Torso")
        local n = part:Clone()
        n.Parent = char

        local weld = Instance.new("Weld",n)
        weld.Part0 = n
        weld.Part1 = torso
    end)
end)

Hope I helped!

~TDP

Ad
Log in to vote
3
Answered by 7 years ago
Edited 7 years ago

If you think this script is confusing, you can split this script into functions. Eg. you can type a new function for welding process by typing:

function Welding(p1,p2)
local w = Instance.new('Weld', p1) 
w.Part0 = p1
w.Part1 = p2
w.C0 = CFrame.new(0,0,0)

and you can call this function from while loop by typing:

Welding(Torso,clonedPart)

Edit: Suggestion of TheDeadlyPanther is pretty good too, you can use PlayerAdded and CharacterAdded events to make it less laggy and better process. Also if you use LocalScript you can reach character each time a character spawns. Give it a try, LocalScripts are one of the most lagless and easy type of scripts if you are working on player.

Answer this question