Why Won't my Button Work?

  1. What do you want to achieve? Keep it simple and clear!
    Basically, I am trying to create a button that teleports to random locations when pressed, and creates a model after being pressed.

  2. What is the issue? Include screenshots / videos if possible!
    The issue is that when I press the button, it moves to a random location the first time, but then it stops moving to different locations after I try pressing it again.

  3. What solutions have you tried so far? Did you look for solutions on the Developer Hub?
    I tried print debugging to see if everything was working out fine, and my outputs are telling me that everything is running.

Here is my code for the button:

local debounce = false
local button = script.Parent.Parent -- The script is in a button part. The parent of the button part is the actual button model
local randomX = math.random(-63.375,63.375)
local randomZ = math.random(-66.175,66.175)

local function duplicate(Object)
	local object = Object -- "Object" is going to be the model in the replicated storage
	local copy = object:Clone() -- defining a variable to clone the Object
	copy.Parent = workspace -- Bringing the copy of the object to workspace by giving it a parent
	copy:setPrimaryPartCFrame(CFrame.new(0,0,0)) -- Clone the object at (0,0,0) [My only object to clone is a spinner so far, which is why all the cloned objects will be in the center]
end

function onHit(hit)
	if (hit.Parent:FindFirstChild("Humanoid") ~= nil) and true then
		if not debounce then
			debounce = true -- debounce to make sure button doesn't get hit more than once
			duplicate(game.ReplicatedStorage.Spinner) -- calling the duplicate function
			button:setPrimaryPartCFrame(CFrame.new(randomX,0.65,randomZ)) -- the button will change CFrames, meaning it will teleport somewhere else in the boundaries I set
			wait(2) -- wait(2) before you can press the button again
			debounce = false
		end
	end
end

script.Parent.Touched:connect(onHit)

I will rewrite the code so it spawns a different variety of models soon, but for now, I am more worried about the button. Also, I am rather new to scripting, so I would appreciate it if you could not throw confusing terms at me. I wrote this in a script, not a LocalScript, so notify me if that turns out to become the issue.

This is because you’re assigning fixed variables as randomX and randomY. Change

button:setPrimaryPartCFrame(CFrame.new(randomX,0.65,randomZ))

to

button:setPrimaryPartCFrame(CFrame.new(math.random(-63.375,63.375),0.65,math.random(-63.375,63.375)))

After that, remove the variables altogether.
hth!

2 Likes

Thank you! This really helped!

To better understand the mistake, I tried assigning RandomX and RandomZ to a variable without letting it change again, correct?

Correct. You’re not reassigning the variable, so it uses the first random number it generates every time.