So I've designed a punching mechanic that triggers when you press 'E'; I haven't programmed damage yet, only an animation occurs, but I tested it in game and it didn't work. It works in Studio, what did I do wrong? The error that I get does not show up in studio, but rather in the output bar in-game. "Humanoid is not a valid member of Model"
local player = game:GetService'Players'.LocalPlayer local char = player.Character or player.CharacterAdded:wait() local Hum = char.Humanoid -- This is the Humanoid the error is referring to. local animation = Instance.new("Animation") animation.AnimationId = "rbxassetid://855470374" -- Punching Animation game:GetService("UserInputService").InputBegan:connect(function(Key) if Key.KeyCode == Enum.KeyCode.E then local animTrack = Hum:LoadAnimation(animation) animTrack:Play() -- Initiate the Punching Animation end end)
Initially there was a problem with Char with it loading before the player did, which might somehow be correlated with this issue. If anyone could give any insight on how to fix this, I would be extremely grateful.
http://wiki.roblox.com/index.php?title=API:Class/Instance/WaitForChild
When any script begins, it can't be sure anything is loaded. The "character" you get from CharacterAdded
is merely an empty model at that moment. Use WaitForChild
for any object that isn't a direct parent of the script.
Also it is bad practice to load the animation every single time. You should do it beforehand.. but you have to wait() or else the humanoid is not ready.
Lastly all of these objects might be useless once the player dies; consider using StarterCharacterScripts.
local player = game.Players.LocalPlayer local char = player.Character or player.CharacterAdded:wait() local Hum = char:WaitForChild("Humanoid") local animation = Instance.new("Animation") animation.AnimationId = "rbxassetid://855470374" -- Punching Animation wait() local animTrack = Hum:LoadAnimation(animation) game:GetService("UserInputService").InputBegan:connect(function(Key) if Key.KeyCode == Enum.KeyCode.E then animTrack:Play() -- Initiate the Punching Animation end end)