What's wrong with my code?

I am trying to make a system where when a player is touching a part, and when they press “V”, an animation plays. (I plan on editing more).
Here’s what I have so far:

-- Replace this with the actual part you want to detect touches on
local part = game.Workspace.WaterDrinkFolder.WaterDetection

-- Replace this with the actual animation ID you want to play
local animationId = "rbxassetid://17075750640"

-- Function to handle input
local function onInput(input, gameProcessedEvent)
	if not gameProcessedEvent and input.KeyCode == Enum.KeyCode.V then
		local player = game.Players:GetPlayerFromCharacter(input.UserInputType == Enum.UserInputType.Keyboard and game.Players.LocalPlayer.Character or nil)
		if player then
			local character = player.Character
			if character then
				local humanoid = character:FindFirstChild("Humanoid")
				if humanoid and part:IsPointInRegion(humanoid.RootPart.Position) then
					local anim = Instance.new("Animation")
					anim.AnimationId = animationId
					local playAnim = humanoid:LoadAnimation(anim)
					playAnim:Play()
				end
			end
		end
	end
end

-- Connect the input event
game:GetService("UserInputService").InputBegan:Connect(onInput)

1 Like

Are there any errors? If not then it should be fine. “If it works, don’t touch it”

1 Like

No errors. When I press V nothing happens.

1 Like

I think you should use part:GetTouchingParts() and loop through the parts and check if they’re descendant of character, in which case proceed to playing animation

1 Like

Also I don’t really understand why you declared local player the way you did, you could just do

local player = game.Players.LocalPlayer

Also, you’re using a deprecated way of using animations so please refer to this:

is it okay to still use the depreciated code?

Humanoid still works, however Animator should be the one you are using to load animations, because it is not deprecated.

I think it is because it transforms the deprecated usage into the new one (I believe it creates an animator when you try loading an animation onto humanoid), but long term it’s better to use an animator

I defined it weirdly because it is not a localscript. When I try using animations in local scripts they never work for some reason.

That’s the error. As far as I can remember you cannot use UIS in server. It should be on the client to properly detect player inputs.

Uh, does input service even work in server scripts? I don’t think so, you should rewrite the script to a LocalScript and please use the animator documentation.

alright thank you!
didnt know this way of animation was depreciated.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.