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

How can you make this code smaller so it doesn't seem repetitive?

local button = script.Parent.Spawn1
local button2 = script.Parent.Spawn2
local button3 = script.Parent.Spawn5

local rs = game:GetService('ReplicatedStorage')
local zombie = rs.Objects:FindFirstChild('Drooling Zombie')

button.MouseButton1Click:Connect(function(plr)
	local positionX = math.random(-125, 125)
	local positionZ = math.random(-125, 125)
	local zombieClone = zombie:Clone()
	zombieClone.Parent = workspace:FindFirstChild('Zombies')
	zombieClone:FindFirstChild('HumanoidRootPart').CFrame = CFrame.new(positionX, 15, positionZ)
end)
button2.MouseButton1Click:Connect(function(plr)
	for i = 1,2 do
		local positionX = math.random(-125, 125)
		local positionZ = math.random(-125, 125)
		local zombieClone = zombie:Clone()
		zombieClone.Parent = workspace:FindFirstChild('Zombies')
		zombieClone:FindFirstChild('HumanoidRootPart').CFrame = CFrame.new(positionX, 15, positionZ)
	end
end)
button5.MouseButton1Click:Connect(function(plr)
	for i = 1,5 do
		local positionX = math.random(-125, 125)
		local positionZ = math.random(-125, 125)
		local zombieClone = zombie:Clone()
		zombieClone.Parent = workspace:FindFirstChild('Zombies')
		zombieClone:FindFirstChild('HumanoidRootPart').CFrame = 						CFrame.new(positionX, 15, positionZ)
	end
end)

It just seems repetitive and I was just wondering if this code could be made more compact and smaller

1 answer

✓ Accepted answer

Improvements

Use :WaitForChild() to make sure an instance exists before using it (FindFirstChild can return a nil value)

You don't need to make a local variable for the position elements, they can be calculated inside the CFrame constructor

Use :SetPrimaryPartCFrame() to move the player's Character model

Explanation

You can use the :GetChildren() table of an instance and iterate over it defining your event once for each instance that matches the given conditions, adjusting variables as necessary

Revised Local Script

local rs = game:GetService('ReplicatedStorage')
local zombie = rs:WaitForChild('Objects'):WaitForChild('Drooling Zombie')

for _, button in pairs(script.Parent:GetChildren()) do
	if string.sub(button.Name, 1, 5) == 'Spawn' then
		local num = tonumber(string.sub(button.Name, 6, 6))
		if num == 1 or num == 2 or num == 5 then
			button.MouseButton1Click:Connect(function(plr)
				for c = 1, num, 1 do
					local clone = zombie:Clone()
					clone.Parent = workspace:WaitForChild('Zombies')
					clone:SetPrimaryPartCFrame(CFrame.new(math.random(-125, 125), 15, math.random(-125, 125)))
				end
			end)
		end
	end
end

1 comment

1

wow you went out of your way to make my code even better props to you tysm

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