So basically, I’m trying to create a viewmodel for my weapon.
In a localscript in the tool for the weapon, I added a check to see if the player is jumping, and if so then the jump animation plays. Whenever the player dies, only the code that plays the jump animation breaks.
I tried to add a Player:CharacterAdded:Wait() function inside of the script, but doing this makes the viewmodel disappear altogether. How can I fix it so that the jump animation doesn’t break when the player dies and respawns?
playerhum.StateChanged:Connect(function(old, new)
if not playerhum then return end
if track6.IsPlaying == true then return end
if track5.IsPlaying == true then return end
if new == Enum.HumanoidStateType.Jumping or new == Enum.HumanoidStateType.Freefall then
print("jumped")
track4:Play()
elseif new == Enum.HumanoidStateType.Landed or old == Enum.HumanoidStateType.Jumping or old == Enum.HumanoidStateType.Freefall then
print("landed")
track4:Stop()
end
end)```
Have you tried this: local Character = Player.Charater or Player.CharacterAdded:Wait()
If you only use the CharacterAdded:Wait() then it haults the code until the next time the character respawned. The line i provided continues if there is a character, but if there isnt it waits until a new one is added.
Ok after some research, I found out that it has to do with the fact that the code runs before the character has respawned. What this means is that it takes the old character and old humanoid as the variables and applies the function there. A simple wait() before defining the variables fixed this issue for me.
Here is the way i tested it, in a local script inside of a tool in starterplayer. Without the wait, it prints that the playerhum has 0 health (the old, dead one)
wait()
local plr = game.Players.LocalPlayer
local char = plr.Character or plr.CharacterAdded:Wait()
local playerhum = char:WaitForChild("Humanoid")
print(playerhum.Health)
print("script started")
local function checkState(old, new)
if new == Enum.HumanoidStateType.Jumping then
print("jumping")
elseif new == Enum.HumanoidStateType.Landed and (old == Enum.HumanoidStateType.Jumping or old == Enum.HumanoidStateType.Freefall) then
print("landed")
end
end
playerhum.StateChanged:Connect(checkState)