NPCService (v1.2.5) - An easy way to create NPC

NPCService

Easily create and manage NPCs with aggressive or passive behaviours, including simple combat and wandering logic.

Get it:

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 NPCLogic should 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 _chaseTarget part is no longer within sight of the NPC, they enter a state of smart chasing. If this continues for ChaseTimeout seconds, 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 isAggressive is set to true upon instantiation.
  • Returns to the origin if no players are within sight for ChaseTimeout seconds.
  • Attacks when their _chaseTarget is within AttackRange studs with a cooldown of AttackCooldown seconds.
Passive Behaviour

Passive Behaviour:

  • Nothing will happen other than wandering if enabled.
Player Detection

Player Detection

  • Detects player if they are within the sight of the NPC, i.e. within MaxSightDistance and MaxSightAngle. In other words, within its detection cone.
Respawning

Respawning:

  • Respawns the NPC if canRespawn is set to true upon instantiation. This will not work if your game doesn’t have SETTINGS.NPC_STORAGE set or your NPC model is not found inside SETTINGS.NPC_STORAGE.
  • If respawnAtOrigin is set to true upon instantiation, NPC respawns at their origin CFrame, if not, the position where they died.
Wandering

Wandering:

  • Wanders around during idle if canWander is set to true upon instantiation.
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 enable isAggressive for tagged NPC

  • NPC_RESPAWN_TAG, the tag needed to enable canRespawn for tagged NPC

  • NPC_RESPAWN_AT_ORIGIN_TAG, the tag needed to enable respawnAtOrigin for tagged NPC

  • NPC_WANDER_TAG, the tag needed to enable canWander for 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 true
  • canRespawn: Respawns after death
  • respawnAtOrigin: Determines respawn position
  • canWander: Enables wandering during idle
  • pathConfig: The AgentParams table used in PathfindingService
  • customLogic: The logic values used for behaviour inside NPCLogic
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

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 NPCLogic properties 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 argument customLogic: {}.
  • There was an issue where NPC would completely break when culled and then spawned back (only if canWander is 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.
Did you find this useful?
  • Yes
  • Maybe
  • No
0 voters
20 Likes

v1.1.0 Changelogs:

  • 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 NPCLogic properties config upon instantiation in the next update.
3 Likes

It’s a great system with customization

3 Likes

v1.2.0 Changelogs:

  • 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 argument customLogic: {}.
  • There was an issue where NPC would completely break when culled and then spawned back (only if canWander is set to true). This is now fixed.
1 Like

this looks really well put together, i like how you kept the setup simple but still added useful features like culling and custom logic. definitely going to test this out in my game

1 Like

v1.2.5 Changelogs:

  • Rewritten some unnecessary parts of the code.
  • Fixed NPCService: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 logic (see example above).
  • Fixed a bug where NPCs would stutter and return to the origin because of a code mistake.
  • Changed some default values.
2 Likes

How am I supposed to implement custom logic using this system? I tried in mine and it doesn’t work


(npcserviceReference variable is the actual module path itself, not wrapped in a require statement, needed to access the path to the custom behavior)

1 Like

is it possible for you add custom attack funtions to then execute that will actually function well in terms of load and stuff?

for attacking, or abilities, or actions.

Please help, someone who knows :broken_heart:

It’s been one day and there’s only someone who tried asking for help too