How to make idle animation play once and not repeat

I have thinking animation that is meant to play ONCE every 7 seconds when the player has not moved for that amount of time. However, the animation currently repeats indefinitely until the players moves, and doesn’t stop when they move until the animation is finished, What I want it to do, is play every 7 seconds once, and stop immediately when the player inputs… input?

local run = game:GetService("RunService")
local userInput = game:GetService("UserInputService")

local lastActivity = tick()

local animation = script.Parent:WaitForChild("Humanoid").Animator:LoadAnimation(script:WaitForChild("Anim"))

run.RenderStepped:Connect(function()
	if tick() - lastActivity > 7 and animation.IsPlaying == false then
		animation:Play()
	end
end)

userInput.InputChanged:Connect(function(input)
	lastActivity = tick()
end)

Hi, this can be done by

run.RenderStepped:Connect(function()
	if tick() - lastActivity > 7 and animation.IsPlaying == false then
		animation:Play()
		animation.Stopped:Wait()
		lastActivity = tick()
	end
end)
3 Likes

Furthermore, your script can be optimized by using

local connection
local function animationFunction()
	if tick() - lastActivity > 7 then
		connection:Disconnect()
		animation:Play()
		animation.Stopped:Wait()
		lastActivity = tick()
		connection = run.RenderStepped:Connect(animationFunction)
	end
end
connection = run.RenderStepped:Connect(animationFunction)

which should work

local Game = game
local Script = script
local UserInputService = Game:GetService("UserInputService")
local Character = Script.Character
local Humanoid = Character:FindFirstChildOfClass("Humanoid") or Character:WaitForChild("Humanoid")
local Animator = Humanoid:FindFirstChildOfClass("Animator") or Humanoid:WaitForChild("Animator")
local Animation = Script:FindFirstChild("Anim") or Script:WaitForChild("Animation")
local Track = Animator:LoadAnimation(Animation)

local LastActivity = os.time()

local function OnInputBegan(InputObject, GameProcessed)
	if GameProcessed then return end
	LastActivity = os.time()
end

UserInputService.InputBegan:Connect(OnInputBegan)

while true do
	if Track.IsPlaying or (os.time() - LastActivity < 7) then continue end
	Track:Play()
	Track.Completed:Wait()
end
1 Like