I’m currently making a game which involves and “auto run” button, which when activated spawns a parts and makes the player walk to it.
I have tried many things like putting the loop in a coroutine or making it a variable and using :Disconnect() but nothing seems to work. My code also involves changing the buttons colour to (which works).
I am relatively new to scripting so sorry if this a stupid mistake that I have made. This is my code
-- SERVICES
local runService = game:GetService("RunService")
local Debris = game:GetService("Debris")
-- VARIABLES
local button = script.Parent
local red = Color3.new(1, 0, 0)
local green = Color3.new(0, 1, 0)
local player = game.Players.LocalPlayer
local character = player.Character
local humanoid = character:FindFirstChild("Humanoid")
local hrp = character:FindFirstChild("HumanoidRootPart")
--COROUTINE
local runCoroutine = coroutine.create(function()
runService.Heartbeat:Connect(function()
local newPart = Instance.new("Part")
newPart.CanCollide = false
newPart.Position = Vector3.new(hrp.Position.X - 10, hrp.Position.Y , 0)
newPart.Parent = workspace
newPart.Anchored = true
newPart.Transparency = 1
humanoid:MoveTo(newPart.Position)
game.Debris:AddItem(newPart, 0.5)
end)
end)
-- MAIN
button.Activated:Connect(function()
if button.BackgroundColor3 == red then
button.BackgroundColor3 = green
task.spawn(runCoroutine)
elseif button.BackgroundColor3 == green then
task.cancel(runCoroutine)
button.BackgroundColor3 = red
end
end)
I don’t know if I’ve done it wrong but it still isn’t working. This is my code
button.Activated:Connect(function()
if button.BackgroundColor3 == red then
local runConnection = runService.Heartbeat:Connect(function()
local newPart = Instance.new("Part")
newPart.CanCollide = false
newPart.Position = Vector3.new(hrp.Position.X - 10, hrp.Position.Y , 0)
newPart.Parent = workspace
newPart.Anchored = true
newPart.Transparency = 1
humanoid:MoveTo(newPart.Position)
game.Debris:AddItem(newPart, 0.5)
if button.BackgroundColor3 == green then
runConnection:Disconnect()
end
end)
end
end)