Cframe.new only working once?

I am trying to script a block to move within a restricted space when clicked on as a practice exercise for myself, which i have succeeded in, but the block only moves once when clicked on. Here is my current script:

local target = game.Workspace.Target
local ClickDetector = Instance.new("ClickDetector")
ClickDetector.Parent = target

local y = math.random(0.5,21.5)
local z = math.random(-5.5,30.5)

ClickDetector.MouseClick:Connect(function()
	--target.Position = Vector3.new(-20.5,y,z)
	target.CFrame = CFrame.new(-20.5,y,z)
	print("clicked")
end)

When clicked on, the print script works endlessly, but the part will only move once, i tried adding a while loop, which then crashed my studio.
Feedback would be greatly appreciated, and please keep in mind I am a beginner trying to learn so it would be nice to not get a super well working but complicated response I wont understand.

Thanks

The math.random() will be the same every time as you’re only declaring it once. Declare it inside the event for it to change each time.

4 Likes