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
8 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.

01while wait() do
02    local Part = game.ReplicatedStorage:WaitForChild('Cop')
03    local plrs = game.Players:GetPlayers()
04    for i = 1, #plrs do
05        local Char = plrs[i].Character
06        local Torso = Char.Torso
07 
08        if not Torso:FindFirstChild('Cop') then
09            local clonedPart = Part:Clone()
10            clonedPart.Parent = Torso
11 
12            local Weld = Instance.new('Weld', Torso)
13            Weld.Part0 = Torso
14            Weld.Part1 = clonedPart
15            Weld.C0 = CFrame.new(0,0,0)
16        end
17    end
18end
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 — 8y
0
Is the an example of what the for loop you are talking about looks like? FiredDusk 1466 — 8y

2 answers

Log in to vote
1
Answered by 8 years ago

Try using the PlayerAdded and CharacterAdded events:

01local part = game:ReplicatedStorage:WaitForChild("Cop")
02 
03game.Players.PlayerAdded:connect(function(p)
04    p.CharacterAdded:connect(function(char)
05        local torso = char:WaitForChild("Torso")
06        local n = part:Clone()
07        n.Parent = char
08 
09        local weld = Instance.new("Weld",n)
10        weld.Part0 = n
11        weld.Part1 = torso
12    end)
13end)

Hope I helped!

~TDP

Ad
Log in to vote
3
Answered by 8 years ago
Edited 8 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:

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

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

1Welding(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