local UIS = game:GetService('UserInputService')
local Players = game:GetService("Players")
local Player = Players.LocalPlayer
local Character = Player.Character or Player.CharacterAdded:Wait()
UIS.InputBegan:connect(function(input,processed)
if processed then return end
if input.KeyCode == Enum.KeyCode.LeftShift then
Character.Humanoid.WalkSpeed = 24
local Anim = Instance.new('Animation')
Anim.AnimationId = 'rbxassetid://10910827063'
PlayAnim = Character.Humanoid:LoadAnimation(Anim)
PlayAnim:Play()
end
end)
UIS.InputEnded:connect(function(input)
if input.KeyCode == Enum.KeyCode.LeftShift then
Character.Humanoid.WalkSpeed = 16
if PlayAnim then
PlayAnim:Stop()
PlayAnim:Destroy()
end
end
end)
What it does:
Simply giving the player running animation when running [ pressing shift].
My Question:
How could I improve this? Although it works, is there a better way to do this?
To best solve this, either create it manually in studio and put it someone where it can be easily referenced, which is what I would recommend, or only define it once outside of your connection.
Also, make sure to call :Destroy() if needed when using the latter, depending on what type of script this is or where you decide to parent it.
What I mean is instancing your Animation instance outside of the InputBegan connection, so you only create it once, and not everytime the shift button is pressed.
Yes, but in the name of improving the readability and the very minor micro-optimizations, instancing it everytime is a bit of a bad practice unless truly needed.
local UIS = game:GetService('UserInputService')
local Players = game:GetService("Players")
local Player = Players.LocalPlayer
local Character = Player.Character or Player.CharacterAdded:Wait()
local Humanoid = Character:WaitForChild("Humanoid")
local Anim = Instance.new('Animation')
Anim.AnimationId = 'rbxassetid://10910827063'
UIS.InputBegan:connect(function(input,processed)
if processed then return end
if input.KeyCode == Enum.KeyCode.LeftShift then
Humanoid.WalkSpeed = 24
PlayAnim = Humanoid:LoadAnimation(Anim)
PlayAnim:Play()
end
end)
Humanoid:GetPropertyChangedSignal("MoveDirection"):Connect(function()
if Humanoid.MoveDirection.Magnitude == 0 then
if PlayAnim then
PlayAnim:Stop()
PlayAnim:Destroy()
end
end
end)
UIS.InputEnded:connect(function(input)
if input.KeyCode == Enum.KeyCode.LeftShift then
Humanoid.WalkSpeed = 16
if PlayAnim then
PlayAnim:Stop()
PlayAnim:Destroy()
end
end
end)