Random animation plays when player takes damage

Hello! I am hoping someone can help me out the best they can, I need help making 4 different animations play when the player takes damage from another player. When the player gets hit I need them to play in a random order I am not too sure how to do this I have also tried for i,v in pairs but I just don’t understand how to play them and make the player take damage if anyone can help thank you!

This is what I tried so far Sorry for the bad scripting.

Help

2 Likes

If you’re looking to generate a random number between 1 and 4, then you could use math.random(1, 4).
Another thing that would help you is if you made an array to list every animation.

local Animations = {
   AnimationFolder.Animation1,
   AnimationFolder.Animation2,
   AnimationFolder.Animation3,
   AnimationFolder.Animation4
}

Then to select the one you could take the output from the random number for the animation.

Animations[math.random(1,4)]:Play()

I hope this post was helpful.

2 Likes

Preferably you would do it like

local Animations = AnimationFolder:GetChildren()

then you could just do

Animations[math.random(#Animations)]:Play()

I know OP specified only 4 animations, this would work just incase they wanted more and no need to edit the code

1 Like

Yes this was very Helpful i appreciate it boss :+1:

image

image

This is what I came up with but it does not work nor print errors :confused:

First of all, LastKnownHealth is only set a value on the inside of the if statement that asks whether it has a set value, so just move it out of the if statement.

game:GetService("RunService").RenderStepped:Connect(function()
   if LastKnownHealth then
      ...
   end
   LastKnownHealth = Humanoid.Health --This is where it needs to be moved to.
end)

Once you do that, the code will run, but it will keep playing the animation every frame which makes it look like nothing is happening. What would work, but I don’t know if it’s the best solution, is to make a while loop and force the code to wait until the animation is done.

local Humanoid = script.Parent.Humanoid
local LastKnownHealth
while true do
   if LastKnownHealth then
      if LastKnownHealth > Humanoid.Health then
         print("Playing")
         local value = math.random(1, 1)
         if value == 1 then
            script.Parent.Parent.ReplicatedStorage.Animation.Ani:Play()
            repeat game:GetService("RunService").RenderStepped:Wait() until script.Parent.Parent.ReplicatedStorage.Animation.Ani.Playing == false
         end
      end
   end
end

(Footnote: Also, in the future, please just copy and paste your code instead of taking a screenshot.)

1 Like

you need to load the animation for it to play

local animation = Humanoid:LoadAnimation(animationhere)
1 Like