Math.random(animation)

Hello!

I’m making a sword system and I would like to know how to make a random animation play every time the player clicks MouseButton1Down, or just every second click go back to the first animation.

How could I do this?

Any help appreciated!

2 Likes
local a = math.random(1,2)
if a == 1 then
swordplayahhhh
else
swordaltplayahhhh
end
2 Likes

Firstly, I suggest making a folder in ReplicatedStorage called “Animations” and store sub folders of each weapon’s animation.

I’m also assuming you’re doing this from a client script in the tool.
You can do this:

local sp = script.Parent

local animations = game.ReplicatedStorage:WaitForChild("Animations"):WaitForChild("SwordSwings")

local plr = game.Players.LocalPlayer
local char = plr.Character or plr.CharacterAdded:Wait()
local animator = char:WaitForChild("Humanoid"):WaitForChild("Animator")

sp.Activated:Connect(function()
    local random = Random.new()
    local randomAnim = random:NextInteger(1,#animations:GetChildren())
    randomAnim:Play()
end)

Or, if you want to play them consecutively, then do this:

local sp = script.Parent

local animations = game.ReplicatedStorage:WaitForChild("Animations"):WaitForChild("SwordSwings")
local swing1 = animations:WaitForChild("Swing1")
local swing2 = animations:WaitForChild("Swing2")

local plr = game.Players.LocalPlayer
local char = plr.Character or plr.CharacterAdded:Wait()
local animator = char:WaitForChild("Humanoid"):WaitForChild("Animator")

local cycle = 1

sp.Activated:Connect(function()
    if cycle == 1 then
        cycle = 2
        animator:LoadAnimation(swing1):Play()
    else
        animator:LoadAnimation(swing2):Play()
        cycle = 1
    end
end)

I am also expecting you to add your own debounce.

3 Likes

This helped, much appreciated!