Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

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

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

2 comments

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.

0

Is the an example of what the for loop you are talking about looks like?

2 answers

✓ Accepted answer

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

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.

This discussion is preserved as it was. New answers, comments, and votes are closed.