Now i know why this doesen't work and it says newAnim is a nil value even though its a global variable?
local p = game.Players.LocalPlayer local anim = script.Animation local serv = game:GetService("UserInputService") local keyCodeQ = Enum.KeyCode.Q local keyCodeE = Enum.KeyCode.E local char = p.Character -- their character if not p.Character then -- checks to see if the character exists repeat wait() until p.Character -- if not, it waits until it exists end local human = char:WaitForChild("Humanoid") -- the character's humanoid (required to load an animation) serv.InputBegan:connect(function(key,processed) if serv:IsKeyDown(keyCodeQ) and serv:IsKeyDown(keyCodeE) then -- change 'F' to your key, also checks to see if a player is typing (etc.) or not print("Starting animation!") newAnim = human:LoadAnimation(anim) newAnim:Play() end end) serv.InputEnded:connect(function(input) if not serv:IsKeyDown(keyCodeQ) and not serv:IsKeyDown(keyCodeE) then newAnim:Stop() end end)
It's due the scope of the variable. First off I would like to say that under no circumstances should you ever define a variable without using local
. In rbx.lua there is absolutely no reason to. Back to the question, as I said, the scope of newAnim
is different than the scope of the listener function. This has a very simple fix, in your variable declarations add
local newAnim
This will delcare the variable with no value (nil).Now line 15 will simply set the value of newAnim rather than declare the variable there. I'm not sure of the exact wording to describe this but, it will work because newAnim will be of a "higher" scope that all of the script is contained in.
If my answer solved your problem please don't forget to mark it correct!