The idea here is, when you fire your gun your character will points towards your mouse, after 5 seconds your character will stop pointing, which works pretty well with this code, the problem is it creates multiple threads.
How would I go about having something break the repeat when I fire my gun again?
local function Point()
HumanoidRootPart.CFrame = CFrame.lookAt(HumanoidRootPart.CFrame.Position, Vector3.new(Mouse.Hit.Position.X, HumanoidRootPart.CFrame.Position.Y, Mouse.Hit.Position.Z))
end
local function WeaponFired()
coroutine.wrap(function()
local Time = os.clock() repeat task.wait() Point() if not Equipped then break end until (os.clock() - Time) >= 5
end)()
end
Honestly you shouldn’t use repeat until because it’s really slow for something you’re doing like
pointing a character to your mouse. You would want it to run at every frame just for smoothness.
local function Point()
HumanoidRootPart.CFrame = CFrame.lookAt(HumanoidRootPart.CFrame.Position, Vector3.new(Mouse.Hit.Position.X, HumanoidRootPart.CFrame.Position.Y, Mouse.Hit.Position.Z))
end
local function WeaponFired()
local Connection
local Time = os.clock()
Connection = game:GetService("RunService").RenderStepped:Connect(function()
Point()
if os.clock() - Time >= 5 or not Equipped then
Connection:Disconnect() -- Stops
end
end)
end
That seems to be doing the same exact thing, reason why it’s creating multiple threads is because I’m calling the WeaponFired() function every time the gun is shot, how would I for example, reset a timer and allow it to keep running as long as I keep shooting.
Right, so every time you shoot the gun you would need to disconnect the thread if it’s running
local Connections = {}
local Time
local function Point()
HumanoidRootPart.CFrame = CFrame.lookAt(HumanoidRootPart.CFrame.Position, Vector3.new(Mouse.Hit.Position.X, HumanoidRootPart.CFrame.Position.Y, Mouse.Hit.Position.Z))
end
local function WeaponFired()
Connections["Point"] = game:GetService("RunService").RenderStepped:Connect(function()
Point()
if os.clock() - Time >= 5 or not Equipped then
Connections.Point:Disconnect()
end
end)
end
local function ShootWeapon() -- Whatever function shoots the weapon
Time = os.clock()
if Connections["Point"] then
Connections.Point:Disconnect()
end
WeaponFired()
end
If you’re using Tools and Equipped is just a proxy bool for the Equipped and Unequipped events, you won’t need to do any messy evaluations or clocking. You can just use RBXScriptConnections.
local function WeaponFire(): ()
local OnStepped: RBXScriptConnection = RunService.Stepped:Connect(Point)
local function Disconnect_OnStepped(): ()
OnStepped:Disconnect()
end
Tool.Unequipped:Once(Disconnect_OnStepped)
task.delay(5, Disconnect_OnStepped)
end