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

How to simplify this code, so if add more blocks I don't have to write it?

Blocks are in tables and I was wondering how to simplify this code so that I don't have to write it over and over again:

rs = game.ReplicatedStorage
local block = {
	rs:WaitForChild("StoneBlock"),
	rs:WaitForChild("DimondBlock")
}
	
local dimondChance = 0.1
	
local rand = math.random()
if rand < dimondChance then
	local clonedblock = block[2]:Clone()
	clonedblock.Parent = folder --destination folder
	clonedblock:SetPrimaryPartCFrame(CFrame.new(x, y, z))
else 
	local clonedblock = block[1]:Clone()
	clonedblock.Parent = folder --destination folder
	clonedblock:SetPrimaryPartCFrame(CFrame.new(x, y, z))
end

Thanks for the Help!

1 answer

✓ Accepted answer

When code is repeated like this you can pull the repeated code out into a function and just pass in the parts that change as variables. Something like this:

rs = game.ReplicatedStorage
local block = {
	rs:WaitForChild("StoneBlock"),
	rs:WaitForChild("DimondBlock")
}

local dimondChance = 0.1

local function CreateBlock(blockType)
	local clonedblock = blockType:Clone()
	clonedblock.Parent = folder --destination folder
	clonedblock:SetPrimaryPartCFrame(CFrame.new(x, y, z))
end

local rand = math.random()
if rand < dimondChance then
	CreateBlock(block[2])
else 
	CreateBlock(block[1])
end

2 comments

0

just an FYI math.random((1/10), (10/10))

0

whats that gonna do? if you put no arguments it generates a pseudo number from 0 to 1

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