NPCService
Easily create and manage NPCs with aggressive or passive behaviours, including simple combat and wandering logic.
Get it:
- Creator Store: https://create.roblox.com/store/asset/88389726359588/NPCService
- File: NPCService.rbxm (19.9 KB)
- GitHub: GitHub - oFeela/NPCService · GitHub
Overview
NPCService is a modular, reusable system to help create and manage server-sided NPCs efficiently. I decided to create this module because I wanted to minimize lag as much as possible while still using the server as the handler. As you may know, there are ways to make NPCs run locally, but then it gets quite complicated against exploiters.
Architecture
Each NPC is assigned to an NPCController that handles its state on the server:
- Spawning
- Despawning
- Culling (disables all running threads when they don’t need to be rendered)
- Path using SimplePath
- Any info unrelated to
NPCLogicshould be put here
Each NPCController also has its own NPCLogic to handle every movement/AI-related behaviour.
Features
Smart Chasing
Smart Chasing:
- Uses SimplePath module modified with type checking added for ease of use.
- When
_chaseTargetpart is no longer within sight of the NPC, they enter a state of smart chasing. If this continues forChaseTimeoutseconds, NPC will return to the origin. This is done for the realism aspect.
Aggressive Behaviour
Aggressive Behaviour:
- Detects for nearby players within a detection cone and chases after them if
isAggressiveis set totrueupon instantiation. - Returns to the origin if no players are within sight for
ChaseTimeoutseconds. - Attacks when their
_chaseTargetis withinAttackRangestuds with a cooldown ofAttackCooldownseconds.
Player Detection
Player Detection
- Detects player if they are within the sight of the NPC, i.e. within
MaxSightDistanceandMaxSightAngle. In other words, within its detection cone.
Respawning
Respawning:
- Respawns the NPC if
canRespawnis set to true upon instantiation. This will not work if your game doesn’t haveSETTINGS.NPC_STORAGEset or your NPC model is not found insideSETTINGS.NPC_STORAGE. - If
respawnAtOriginis set to true upon instantiation, NPC respawns at their origin CFrame, if not, the position where they died.
Culling
Culling:
- Active NPCs are paused temporarily when no nearby players are detected to reduce server load.
- NPC should correctly remember the state they were in.
Basic Usage
local NPCService = require(script.Parent)
local model: Model = Path.To.Your.Model
local controller = NPCService:AddNPC(
model,
{
-- You only need to pass what value you want customize, everything defaults to false
isAggressive = true
},
{
-- The parameter pathConfig defaults to Roblox's default AgentParams for PathfindingService, specify if want custom.
WaypointSpacing = 2 -- Recommended value: >= 2, Roblox's default is 4
},
{
AttackCooldown = 3,
AttackRange = 5
}
)
controller.NPCLogic:ReturnToOrigin() -- Forces to origin return
task.wait(100)
NPCService:RemoveNPC(model)
controller = nil -- Remove reference if no longer used
Please make sure to change the SETTINGS ModuleScript if you wish to change any settings:
-
NPC_STORAGE, the place where your NPC models are stored -
NPC_TAG, the tag needed to identify a model as NPC -
NPC_AGGRESSIVE_TAG, the tag needed to enableisAggressivefor tagged NPC -
NPC_RESPAWN_TAG, the tag needed to enablecanRespawnfor tagged NPC -
NPC_RESPAWN_AT_ORIGIN_TAG, the tag needed to enablerespawnAtOriginfor tagged NPC -
NPC_WANDER_TAG, the tag needed to enablecanWanderfor tagged NPC -
CULLING_FREQUENCY, how often (per second) culling calls are called to check for players -
CULLING_DISTANCE, the maximum distance for NPC to be active -
PATH_VISUALIZE, set to true for waypoints visualization made from the created path
APIs
NPCService:Init()
Instantiates every model with a Humanoid tagged as SETTINGS.NPC_TAG and any custom tags related to behaviourConfig with respect to SETTINGS tags. Keep in mind that pathConfig and customLogic will be set to the default. It is recommended to manually add them instead by using NPCService:AddNPC().
NPCService:Init()
NPCService:AddNPC()
Creates an NPC manually. Optional arguments have default values if not specified. The recommended value for WaypointSpacing is above 2; otherwise, it won’t work properly!
NPCService:AddNPC(
NPCModel: Model,
behaviourConfig: {
isAggressive: boolean?,
canRespawn: boolean?,
respawnAtOrigin: boolean?,
canWander: boolean?
}?,
pathConfig: {
AgentRadius: integer?,
AgentHeight: integer?,
AgentCanJump: boolean?,
AgentCanClimb: boolean?,
WaypointSpacing: number?,
CostModifiers: {[string]: number}?
}?,
customLogic: {
MaxSightDistance: number?,
MaxSightAngle: number?,
ChaseTimeout: number?,
AttackRange: number?,
AttackCooldown: number?,
ChaseDetectionInterval: number?,
}?
): NPCController
isAggressive: NPC chases players if truecanRespawn: Respawns after deathrespawnAtOrigin: Determines respawn positioncanWander: Enables wandering during idlepathConfig: TheAgentParamstable used in PathfindingServicecustomLogic: The logic values used for behaviour insideNPCLogic
NPCService:RemoveNPC()
Removes an existing NPC (destroys the NPC’s Controller and Logic. Does not destroy the model).
NPCService:RemoveNPC(NPCModel: Model)
Custom APIs
There is type checking implemented in this module, so you can easily check what methods are available. For example:
...
local controller = NPCService:AddNPC(
model,
{
-- You only need to pass what value you want customize, everything defaults to false
isAggressive = true
},
{
-- The parameter pathConfig defaults to Roblox's default AgentParams for PathfindingService, specify if want custom.
WaypointSpacing = 2 -- Recommended value: >= 2, Roblox's default is 4
},
{
AttackCooldown = 3,
AttackRange = 5
}
)
controller.NPCLogic:ReturnToOrigin() -- Forces to origin return
...
Custom Logic (Inheritance)
You can extend NPCLogic by creating a new ModuleScript named your NPC’s model. Be sure to parent it under NPCLogic ModuleScript. Below is an example code that makes your NPC randomly die when there is a nearby player:
-- Modules
local UtilityFunctions = require(script.Parent.Parent.Dependencies.UtilityFunctions)
-- Classes
local NPCLogic = require(script.Parent)
local InheritedLogic = {}
InheritedLogic.__index = InheritedLogic
export type InheritedLogic = typeof(setmetatable({}, InheritedLogic)) & NPCLogic.NPCLogic
function InheritedLogic.new(
nameId: string,
NPCController: Types.NPCController,
customLogic: {
MaxSightDistance: number?,
MaxSightAngle: number?,
ChaseTimeout: number?,
AttackRange: number?,
AttackCooldown: number?,
ChaseDetectionInterval: number?,
}?
): InheritedLogic
local self = setmetatable(NPCLogic.new(nameId, NPCController, customLogic) :: InheritedLogic, InheritedLogic)
return self
end
-- Override :InitCustomLogic() for custom behaviour
function InheritedLogic.InitCustomLogic(self: InheritedLogic)
-- Example: Make NPC randomly dies when there is a player nearby
UtilityFunctions:AddThread(self._threads, "CustomerDetection", function()
local hum = self.NPCController.NPCModel:FindFirstChildOfClass("Humanoid")
while task.wait(3) do
if not hum then return end
local nearestChar, dist = self:GetClosestPlayerCharInSight()
if nearestChar and dist < 20 and math.random(1, 100) <= 40 then
hum:TakeDamage(math.huge)
end
end
end)
end
-- Override :Attack()
function InheritedLogic.Attack(self: InheritedLogic)
self:CustomNewMethod()
end
-- Making custom method for custom logic (example)
function InheritedLogic.CustomNewMethod(self: InheritedLogic)
warn("THIS IS A CUSTOM")
end
-- Set at the end for type checking to fully work
setmetatable(InheritedLogic, NPCLogic)
return InheritedLogic
Credits
- SimplePath by grayzscale: Used for NPC pathfinding. Modified with type checking for ease of use.
Disclaimers
This is my first time open-sourcing a module. I’m still learning and would really appreciate any feedback, suggestions, or bug reports. Feel free to use or modify this for your own projects, but keep the original author.
I did not use any Maid or Janitor library in this module because I wanted to keep it accessible for anyone who does not use them. All cleanup and resource management is handled manually, so there may be some issues with dereferencing or connection cleanup. If you notice any memory leaks or unexpected behaviour, let me know.
Changelogs
v1.1.0
- Optimized the way path was computed.
- Changed path computation to use SimplePath events instead of a loop.
- More customizable instantiation parameters.
- No longer uses :MoveTo() when possible as this doesn’t allow Humanoid.Jump to trigger.
- Will add the option to customize
NPCLogicproperties config upon instantiation in the next update.
v1.2.0
- Added a way to instantiate new NPC with custom properties of the NPC’s logic (e.g.
AttackRange,AttackCooldown,ChaseDetectionInterval, etc.) - Consequently,
NPCService:AddNPC()now takes one more argumentcustomLogic: {}. - There was an issue where NPC would completely break when culled and then spawned back (only if
canWanderis set to true). This is now fixed.
v1.2.5
Minor update:
- Rewritten some unnecessary parts of the code.
- Fixed :Init() to actually use CollectionService instead of looping through descendants of Workspace (I forgot to do this somehow).
- Added a way to add a custom behaviour logic. Do this by overriding
:InitCustomLogic()method inside your custom NPCLogic (see example above). - Fixed a bug where NPCs would stutter and return to the origin because of a code mistake.
- Changed some default values.
- Yes
- Maybe
- No
