I am making a tool that plays an animation when you equip it. By pressing either the Q or E key, you can toggle between two different animations. It also changes the character’s face depending on which animation is toggled, and then changes it back when the tool is unequipped. This is all done in a LocalScript:
local RS = game:GetService("ReplicatedStorage")
local UIS = game:GetService("UserInputService")
local Module = require(script.Parent) ---module contains variables for things such as the tool, folder containing the sounds to be played, etc. this is only necessary since another script in this tool needs the same variables
local plr = Players.LocalPlayer
local char
local hum
local playAnimLeft
local playAnimRight
local oldFace
local newFace
local faceTexture
local direction = 0
local inputConnection
function ReplicateFace(face, texture) ---the purpose of this function is to change the player's face on the client (so it appears for the player faster) and then replicate that change to the server
Module.ChangeFace(face, texture)
Module.FaceRemote:FireServer(face, texture)
end
function ChangePose(input, gameProcessed)
if input.KeyCode == Enum.KeyCode.Q or input.KeyCode == Enum.KeyCode.E then
if direction == 1 then
direction = 0
playAnimRight:Play()
playAnimLeft:Stop()
newFace = Module.RightTX
else
direction = 1
playAnimRight:Stop()
playAnimLeft:Play()
newFace = Module.LeftTX
end
ReplicateFace(faceTexture, newFace)
Module.Sounds.woosh:Play()
Module.Sounds.equip:Play()
end
end
Module.Tool.Equipped:Connect(function()
char = char or Module.Tool.Parent or plr.Character or plr.CharacterAdded:Wait()
hum = hum or char:WaitForChild("Humanoid")
faceTexture = char.Face.FaceTexture
oldFace = faceTexture.Texture
if not playAnimLeft or not playAnimRight then
playAnimLeft = hum:LoadAnimation(D.Tool.Left)
playAnimRight = hum:LoadAnimation(D.Tool.Right)
end
if direction == 1 then
playAnimLeft:Play()
newFace = Module.LeftTX
else
playAnimRight:Play()
newFace = Module.RightTX
end
ReplicateFace(faceTexture, newFace)
Module.Sounds.equip:Play()
Module.Sounds.woosh:Play()
inputConnection = UIS.InputBegan:Connect(ChangePose)
end)
Module.Tool.Unequipped:Connect(function()
inputConnection:Disconnect()
playAnimLeft:Stop()
playAnimRight:Stop()
ReplicateFace(faceTexture, oldFace)
Module.Sounds.unequip:Play()
end)
This code works as intended, but it is really messy. I’ve tried to implement ModuleScripts and adhere to the “do one thing, but do it well” scripting principle in some of my work recently, but progress often comes to a halt because I don’t know how to incorporate either into tools when each feature of this tool is so heavily intertwined.
TL;DR how would I clean this code up? Would it be necessary or beneficial to incorporate ModuleScripts into this at all?