Shortening CFrame Positioning Code

Code is too lengthy.

I am trying to find a way to shorten this code. What the code does, is takes 20 invisible parts in a folder, and makes the key that players are trying to find, be in one of these positions (20 different random positions) so I can increase replayability.

  1. The issue is, I have many of these scripts in my game, and it is very tedious to type out 20 elseifs when I’m looking for efficiency.

  2. I’ve tried tables, it breaks.

nothing is wrong with the code it works fine

local chance = math.random(1,20)

local keyFolder = game.Workspace.KeyPositions

local key = script.Parent

wait (5)

print ("The random position landed on " .. chance .. ".")

if chance == 1 then 
	key.CFrame = keyFolder.KeyPosition1.CFrame
elseif chance == 2 then
	key.CFrame = keyFolder.KeyPosition2.CFrame
elseif chance == 3 then
	key.CFrame = keyFolder.KeyPosition3.CFrame
elseif chance == 4 then
	key.CFrame = keyFolder.KeyPosition4.CFrame
elseif chance == 5 then
	key.CFrame = keyFolder.KeyPosition5.CFrame
elseif chance == 6 then
	key.CFrame = keyFolder.KeyPosition6.CFrame
elseif chance == 7 then
	key.CFrame = keyFolder.KeyPosition7.CFrame
elseif chance == 8 then
	key.CFrame = keyFolder.KeyPosition8.CFrame
elseif chance == 9 then
	key.CFrame = keyFolder.KeyPosition9.CFrame
elseif chance == 10 then
	key.CFrame = keyFolder.KeyPosition10.CFrame
elseif	chance == 11 then
	key.CFrame = keyFolder.KeyPosition11.CFrame
elseif chance == 12 then
	key.CFrame = keyFolder.KeyPosition12.CFrame
elseif chance == 13 then
	key.CFrame = keyFolder.KeyPosition13.CFrame
elseif chance == 14 then
	key.CFrame = keyFolder.KeyPosition14.CFrame
elseif chance == 15 then
	key.CFrame = keyFolder.KeyPosition15.CFrame
elseif chance == 16 then
	key.CFrame = keyFolder.KeyPosition16.CFrame
elseif chance == 17 then
	key.CFrame = keyFolder.KeyPosition17.CFrame
elseif chance == 18 then
	key.CFrame = keyFolder.KeyPosition18.CFrame
elseif chance == 19 then
	key.CFrame = keyFolder.KeyPosition19.CFrame
elseif chance == 20 then
	key.CFrame = keyFolder.KeyPosition20.CFrame
elseif chance ~= 1 or 2 or 3 or 4 or 5 or 6 or 7 or 8 or 9 or 10 or 11 or 12 or 13 or 14 or 15 or 16 or 17 or 18 or 19 or 20 then
	key.CFrame = script.Parent.CFrame
end
local key = script.Parent
local keyFolder = game.Workspace.KeyPositions:GetChildren()

local chance = math.random(1, #keyFolder)

wait(5)

print("The random position landed on " .. chance .. ".")

key.CFrame = keyFolder[chance].CFrame
1 Like

Thank you! This will definitely save me some time!

1 Like

You would have to do it like this:

local chance = math.random(1,20)

local keyFolder = game.Workspace.KeyPositions

local key = script.Parent

wait (5)

print ("The random position landed on " .. chance .. ".")

local cframe = keyFolder:FindFirstChild("KeyPosition"..chance).CFrame

if cframe then
	key.CFrame = cframe
else
	key.CFrame = script.Parent.CFrame
end
2 Likes