I am making a restaurant game where the food does random effects, and I want to make it that it will speed up the player, wait 5 seconds, slow down the player, wait another 5 seconds, and then make the walkspeed normal, but the wait() statements aren’t working
caffeine = function(plr)
local val = 24
task.spawn(function()
local char = plr.Character
local hum = char:WaitForChild("Humanoid")
local Info = TweenInfo.new(2)
local Tween = game:GetService("TweenService"):Create(hum,Info,{WalkSpeed=val})
Tween:Play()
task.wait(5)
val = 12
Tween = game:GetService("TweenService"):Create(hum,Info,{WalkSpeed=val})
Tween:Play()
task.wait(5)
val = 16
Tween = game:GetService("TweenService"):Create(hum,Info,{WalkSpeed=val})
Tween:Play()
end)
Tween:Play() does not yield. Tweens play asynchronously, meaning task.wait(5) runs immediately after Tween:Play(), potentially causing issues if the tween isn’t finished before the next step.
caffeine = function(plr)
local char = plr.Character
if not char then return end
local hum = char:FindFirstChild("Humanoid")
if not hum then return end
local tweenService = game:GetService("TweenService")
local info = TweenInfo.new(2)
task.spawn(function()
-- Speed Up
local tween = tweenService:Create(hum, info, {WalkSpeed = 24})
tween:Play()
tween.Completed:Wait() -- Ensure the tween fully plays
task.wait(5)
-- Slow Down
tween = tweenService:Create(hum, info, {WalkSpeed = 12})
tween:Play()
tween.Completed:Wait()
task.wait(5)
-- Normalize
tween = tweenService:Create(hum, info, {WalkSpeed = 16})
tween:Play()
end)
end
local TweenService = game:GetService("TweenService")
local Players = game:GetService("Players")
local function caffeine()
local plr = Players.LocalPlayer
local char = plr.Character or plr.CharacterAdded:Wait()
local hum = char:FindFirstChildOfClass("Humanoid")
if not hum then return end
local function tweenWalkSpeed(speed, duration)
local tween = TweenService:Create(hum, TweenInfo.new(duration, Enum.EasingStyle.Linear), {WalkSpeed = speed})
tween:Play() task.wait(duration)
end
tweenWalkSpeed(24, 2) task.wait(5)
tweenWalkSpeed(12, 2) task.wait(5)
tweenWalkSpeed(16, 2)
end
task.wait(5) --so I have time to get to and see WalkSpeed changing, while testing
caffeine()
I believe your issue was not waiting for the tween to finish.
tween:Play() task.wait(2) … or
tween:Play() tween.Completed:Wait() … or
tween:Play() task.wait(duration) … as I passed duration
This, in turn, threw off the overall timing.
I’m not sure why you would want to use task.spawn() here.