Script stops working when tool reequipped

So i have a script which makes the animation play when theres “GunFiredM4A1” Printed Out.
or “ReloadM4A1”
When i reequip the tool (Destroyng the vmodel and taking it back to camera) the script stops working.

Heres the code of it (localscript it starterplayerscripts)

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Players = game:GetService("Players")
local LogService = game:GetService("LogService")

local player = Players.LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()

local function setupViewModel()
	-- Destroy existing viewmodel if it exists
	if workspace.CurrentCamera:FindFirstChild("ViewModel") then
		workspace.CurrentCamera.ViewModel:Destroy()
	end

	-- Clone the viewmodel from ReplicatedStorage
	local viewmodel = ReplicatedStorage:WaitForChild("ViewModel"):Clone()
	viewmodel.Parent = workspace.CurrentCamera

	-- Get the Animator
	local animator = viewmodel:WaitForChild("Humanoid"):WaitForChild("Animator")

	-- Load the animations
	local Ranimation = Instance.new("Animation")
	Ranimation.AnimationId = "rbxassetid://70861748308924" -- Replace with your animation ID
	local RanimationTrack = animator:LoadAnimation(Ranimation)
	local REanimation = Instance.new("Animation")
	REanimation.AnimationId = "rbxassetid://107805906963968" -- Replace with your animation ID
	local REanimationTrack = animator:LoadAnimation(REanimation)

	-- Function to play the animations
	local function RecoilAnimation()
		RanimationTrack:Play()
	end
	local function ReloadAnimation()
		REanimationTrack:Play()
	end

	-- Connect the log messages to the animations
	LogService.MessageOut:Connect(function(message, messageType)
		if message == "GunFiredM4A1" then
			RecoilAnimation()
		elseif message == "ReloadM4A1" then
			ReloadAnimation()
		end
	end)
end

Hope yall can help!

2 Likes

That’s probably due to the previous connection to LogService.MessageOut is lost, to fix it you should call setupViewModel() everytime the tool is equipped.

1 Like

is there just smth in studio like call x() ?

Can you show me the full script because i didn’t understand you.

the full script is on the topic. I understand that i put everything into a function and call it when the tool is equipped?

Yes, call it whenever the equipped event is fired.

ok ill try it and see if it fixes the problem

1 Like

Worked! Tysm for solving it :smiley:.

1 Like

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