i made a module script for handling idle animations for different NPC’s. i have a script in each NPC model with the idle animation in the script. anything wrong with what i’m doing or can i improve the way i’m doing things?
apologies if this is the wrong category for this post. :3
local NPCAnimator = {}
function NPCAnimator:PlayIdle(npcModel : Model)
local Humanoid : Humanoid = npcModel:FindFirstChildOfClass("Humanoid")
if not Humanoid then warn(npcModel.Name.." has no humanoid.") return end
local animator : Animator = Humanoid:FindFirstChildOfClass("Animator")
if not animator then warn(npcModel.Name.." has no animator.") return end
local idleScript = npcModel:FindFirstChild("IdleAnimation")
local idleAnim = idleScript:FindFirstChild("idle")
if not idleAnim then warn(npcModel.Name .. " missing idle animation") return end
local idleAnimTrack = animator:LoadAnimation(idleAnim)
idleAnimTrack:Play()
end
return NPCAnimator
if you really wanted to, you could add a tag to animated NPC’s, and an attribute with the animation id, then get all the tagged npcs and play their respective animations
local NPCAnimator = {}
local CollectionService = game:GetService("CollectionService")
function NPCAnimator:AnchorHumanoidRootPart(npcModel)
local HumanoidRootPart = npcModel:FindFirstChild("HumanoidRootPart")
if not HumanoidRootPart then
warn(npcModel.Name.." has no HumanoidRootPart!")
return
end
HumanoidRootPart.Anchored = true
end
function NPCAnimator:PlayIdle(npcModel : Model)
local Humanoid : Humanoid = npcModel:FindFirstChildOfClass("Humanoid")
if not Humanoid then warn(npcModel.Name.." has no humanoid.") return end
local animator : Animator = Humanoid:FindFirstChildOfClass("Animator")
if not animator then warn(npcModel.Name.." has no animator.") return end
local animId = npcModel:GetAttribute("AnimationId")
if not animId then warn(npcModel.Name.." is missing AnimationId attribute.") return end
local idle = Instance.new("Animation")
idle.Name = "idle"
idle.AnimationId = "rbxassetid://"..animId
idle.Parent = npcModel
local idleAnimTrack = animator:LoadAnimation(idle)
NPCAnimator:AnchorHumanoidRootPart(npcModel)
idleAnimTrack:Play()
end
for _, npc in ipairs(CollectionService:GetTagged("AnimatedNPC")) do
NPCAnimator:PlayIdle(npc)
end
return NPCAnimator
AnimationHandler (server script):
local NPCAnimator = require(game.ReplicatedStorage.Scripts.NPCAnimator)