Animation Not Playing OnTouch

So I made this script where on touch it plays animation and if ontouch is false then it stops animation but it does work. Here is so the script:

local part = script.Parent
local Player = game.Players.LocalPlayer
local Character = Player.Character

if part.Touched then
	Character.Humanoid.WalkSpeed = 35  --run speed
	local Anim = Instance.new('Animation')
	Anim.AnimationId = 'rbxassetid://15602355960'
	PlayAnim = Character.Humanoid:LoadAnimation(Anim)
	PlayAnim:Play()
end

if part.Touched == false then
	PlayAnim:False()
end

This is what everything looks like:

Screenshot 2023-12-10 143118


Screenshot 2023-12-10 143244

It is just playing my regular animations in the water.

5 Likes

try this

local part = script.Parent
local Player = game.Players.LocalPlayer
local Character = Player.Character

local Anim = Instance.new('Animation')
Anim.AnimationId = 'rbxassetid://15602355960'
PlayAnim = Character.Humanoid:LoadAnimation(Anim)

part.Touched:Connect(function()
	Character.Humanoid.WalkSpeed = 35  --run speed
        PlayAnim:Play()
end)

part.TouchedEnded:Connect(function()
	PlayAnim:Stop()
end)

if that works then great, if it doesn’t please show the output if there are any errors.

and i also would recommend making it a server script if it isn’t already as local scripts cannot run in workspace.

2 Likes

It appears that you are using an if statement instead of an event.
Try

local part = script.Parent
local Player = game.Players.LocalPlayer
local Character = Player.Character

part.Touched:Connect(function(otherpart)
for i,v in pairs(Character:GetChildren()) do
     if otherpart == v then
	Character.Humanoid.WalkSpeed = 35  --run speed
	local Anim = Instance.new('Animation')
	Anim.AnimationId = 'rbxassetid://15602355960'
	PlayAnim = Character.Humanoid:LoadAnimation(Anim)
	PlayAnim:Play()
end
end)
1 Like

For more info on events watch this, which helped me learn events, too.

2 Likes

I think the problem is that the local script is not inside the starterPlayerScripts or the starterCharacterScripts, from the line that says “local part = script.Parent” I understand that the local script is not inside the player, so it will not work, I have It is understood that local scripts only work if they are in the player, in some child of the player or in the player character, if they are in anything that is not related to the player instances, it will not work

2 Likes

I already investigated and if I was right in what I said:

Localscripts can only run when they are a descentant of PlayerScripts, PlayerGui, Backpack or Startergear (when located in the Player object). When you add your own folders to the Player object, and add localscripts to it, they will not run (as far as i know)

hope that helps!

2 Likes