Script that runs animation when mouse clicked isn't working

In ServerStorage, I have a tool (it’s a sunscreen bottle) and inside I have a local script.
Screen Shot 2021-08-23 at 10.01.16 AM

Script:

local player = game.Players.LocalPlayer

repeat wait() until player.Character
local character = player.Character
local humanoid = character:WaitForChild("Humanoid")

local tool = script.Parent 

local animation = Instance.new("Animation")
animation.AnimationId = "rbxassetid://7238904032"

local loaded = humanoid:LoadAnimation(animation)

tool.Equipped:Connect(function(mouse)
	mouse.Button1Down:Connect(function()
		loaded:Play()
	end)
end)

This parameter I believe is like, REALLY OLD (I think it’s deprecated actually), you should consider using the tool.Activated event instead

local player = game.Players.LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()
local Animator = character:WaitForChild("Humanoid"):WaitForChild("Animator")

local tool = script.Parent 

local animation = Instance.new("Animation")
animation.AnimationId = "rbxassetid://7238904032"

local loaded = Animator:LoadAnimation(animation)

tool.Activated:Connect(function()
	loaded:Play()
end)

Also couple side notes that are unrelated (But should still point out):

  • Use the CharacterAdded:Wait() event so that in case the Character doesn’t properly load on time, you can yield for it until there is a proper Character

  • humanoid:LoadAnimation is deprecated by the more former Animator:LoadAnimation function, use that instead

2 Likes
local player = game.Players.LocalPlayer

repeat wait() until player.Character
local character = player.Character
local humanoid = character:WaitForChild("Humanoid")

local tool = script.Parent 

local animation = Instance.new("Animation")
animation.AnimationId = "rbxassetid://7238904032"

local loaded = humanoid:LoadAnimation(animation)

tool.Activated:Connect(function()
  loaded:Play()
end)

Just an example since this would make it so the player can spam the animation.

You can add a debonce and a loaded.Stopped:Wait() to yield it while it’s still playing.

local Debounce = false

tool.Activated:Connect(function()
  if not Debounce then
    Debounce = true  
    loaded:Play()
    loaded.Finished:Wait()
    Debounce = false
  end
end)
2 Likes

I used the script but then I added the mouse part tool.Activated:Connect(function(mouse) mouse.Button1Down:Connect(function() loaded:Play() end) end) but it didn’t work and I want to keep the mouse click part to make the tool more interactive

This didn’t work either (character limit oioioioioioioi)