All products

np_npchandler

The one place the np_* resources get their NPCs from. A resource describes a ped once. The handler decides who gets it, spawns it near players, hides and deletes it when they leave, dresses it, runs its idle behaviour, offers its interaction and cleans up when the owning resource stops.

v1.1.0Standalone · ESX · qbx · qbFor developersNot yet run on a live server
Price TBAStore link follows at release
ExportsDocumentation
Version
1.1.0
Status
Specs pass against stubbed natives, not yet run on a live server
Frameworks
Standalone. ESX first, then qbx or qb, for job and gang conditions
Dependencies
None. OneSync for networked NPCs
Interaction
np_hud prompt, ox_target or qb-target, all optional
Admin
np_admin optional, no ACE
Budgets
48 local and 64 networked peds by default
UI
None, no NUI to build
renderDistancespawnDistance 60 m+ despawnMargin 10 m1234

Where the player stands

  1. Close: spawned and shown. Spawns go nearest-first, two per pass.
  2. Past an optional renderDistance: hidden (invisible, no collision), never deleted for it.
  3. Just past spawnDistance: kept for another 10 m, so standing on the edge doesn't spawn and delete it over and over.
  4. Further out: hidden at once and deleted after 10 s. Walk back in time and the same ped shows again.
server.luaLester for np_gangs, from the README
exports.np_npchandler:registerNpc({
  id = 'np_gangs:lester',
  model = 'ig_lestercrest',
  coords = vector4(1273.9, -1719.7, 54.77, 25.0),
  scenario = 'WORLD_HUMAN_CLIPBOARD',
  spawnDistance = 60.0,
  interact = { label = 'Talk', icon = 'comments', event = 'np_gangs:lester:open' },
})

np_npchandler has no UI. The diagram shows the defaults for a local NPC in shared/config.lua, not to scale. Networked NPCs use 120 m, a 15 m margin and 15 s.

What's in it

Register once, and the handler owns availability, spawn and despawn, render and derender. One streaming loop and one set of budgets instead of a ped loop in every resource.

Two modes

  • Local: a client-side ped per player, streamed by distance. Shopkeepers, desk clerks, Lester, dealers.
  • Networked: one OneSync ped the server creates only while a player in its routing bucket is near, or always with alwaysSpawned.

Streaming and render tier

  • A 2D grid on both sides, only nearby cells scanned, passes skipped while you stand still.
  • Out of range a ped is hidden at once and deleted after a delay. renderDistance hides without deleting.

Availability

  • enabled, routing bucket (pushed from the server), jobs and gangs with a minimum grade.
  • Hours on the in-game clock, wrapping past midnight.

Appearance and behaviour

  • Outfit, held props on a bone, scenario or anim, weapon, relationship group, health, armour, combat values, voice and greetings.
  • Presets: wander, patrol and guard.

Interact

  • Up to six options per NPC, each with its own key, event and conditions: the np_hud prompt, then ox_target, then qb-target.
  • Client predicates hide an option while the player can't use it.
  • An optional built-in E-key text when none of them runs.

Peds you create now

  • Preview peds for creators, client-owned networked peds like a k9, server mission peds in or out of a vehicle.
  • clone = 'player' copies a ped's look, face and tattoos instead of loading a model.
  • All deleted when their owner stops or the player drops.

Runtime control

  • playAnim, playScenario, speak, faceEntity, walkTo, stopTask, resumeBehavior.
  • Networked peds are routed to the client that controls them. Other players can only task an NPC that sets allowRemoteControl, or a ped they created.

Ambient population

  • Stackable density overrides, suppressed areas, scenario type and group toggles.
  • From the client, or from the server and synced to everyone. Opt-in reactions and incidents from v0.2.0.

Budgets and diagnostics

  • A shared ref-counted model loader, ped caps and spawns per tick. getDiagnostics() on both sides.
  • npchandler_debug gated through np_admin, live settings, no ACE.

A closer look

Streaming

Every number is a default in shared/config.lua, and the switches and budgets are live settings in np_admin.

LocalNetworked
Created byEach client, for itselfThe server, one OneSync ped
RegisteredServer or clientServer only
spawnDistance60 m120 m
Despawn margin10 m15 m
Deleted after10 s, hidden in between15 s after the last player left
Budget48 local peds, two spawns per pass64 networked peds, four per tick
  • Grid: NPCs sit in 2D cells. A pass looks only at the cells around the player and is skipped while you stand still.
  • Render tier: out of range a local ped is hidden at once and deleted after despawnDelayMs. Walking back re-shows the same ped.
  • Always there: alwaysSpawned = true keeps a networked ped alive with nobody near, the v0.2.0 anchor.
  • Respawn: a networked ped that is deleted or dies comes back, with delays and a retry limit.
  • Ownership: ids are prefixed with your resource name, only the owner changes or removes an NPC, and everything goes when the owner stops.

Peds you create now

Not streamed, created when you ask. The handler still loads the model, applies the definition and deletes them with their owner.

ExportUse it for
createLocalPedPreview peds: the character creator, the tattoo parlour. Returns a handle at once; the ped arrives in a callback
createNetworkedPedPeds the calling client owns and tasks, like a k9 or a clone of the player. The server issues a ticket first; the callback gets the net ID
createNetworkedPedInVehicleDrivers and passengers the client owns
spawnNetworkedPedServer mission peds, deleted when your resource stops or ownerSource drops
spawnPedInVehicleServer peds in a vehicle, in the vehicle's bucket
dismissPedSend a ped off to wander and delete it later, like a corner customer
local handle = exports.np_npchandler:createLocalPed({
  model = m, coords = vector4(x, y, z, 0.0), frozen = false },
  function(handle, ped)
    if ped ~= 0 then
      exports.np_npchandler:walkTo(handle, corner, { speed = 1.0 })
    end
  end)
...
exports.np_npchandler:dismissPed(handle,
  { wander = true, deleteAfterMs = 20000 })

The definition

Unknown fields are rejected. Any well-formed model, scenario, anim dict, weapon and role is accepted; Config.NpcHandler.restrict narrows that to a list if you want one.

FieldDefault
id, model, coordsRequired. Ids up to 64 characters
mode'local', or 'networked' from the server
spawnDistance60 local, 120 networked, 5 to 400
renderDistanceNone. Below spawnDistance
routingBucketAll for local, 0 for networked
jobs, gangs{ police = 0 } or { 'police' }
hours{ from = 22, to = 6 }, applied on the client
placeOnGroundfalse
FieldDefault
outfit, propsDefault variation, up to 4 held props
scenario or animOne of them
weaponNone
invincible, blockEventstrue
frozentrue, unless a moving preset
wander, patrol or guardOne of them
speechGreeting and interact lines
interact{ name, label, icon, key, distance, event, server, jobs, gangs, hours }, or a list of up to 6

The interact event must start with your resource name and a colon, or be listed in Config.NpcHandler.interactEvents. A server event gets the net ID, a client event the entity, both with the option's name. Options that share a key are picked with the arrow keys.

Ambient population

Overrides stack and are owned by whoever set them. The per-frame density natives only run while one applies.

exports.np_npchandler:setPopulation('np_events:parade', { peds = 0.1, vehicles = 0.0 },
  { coords = vector3(200.0, -900.0, 30.0), radius = 250.0 })
exports.np_npchandler:suppressArea('np_events:stage',
  { coords = vector3(...), radius = 40.0, vehicles = true })
exports.np_npchandler:setScenarioGroups('np_events:no_cops', { POLICE_POUND1 = false })
exports.np_npchandler:clearPopulation('np_events:parade')
  • From the server, the same calls are synced to every client.
  • Reactions: the v0.2.0 perception, policy, dialogue cue and incident system stays, opt-in per networked NPC with a perception field.
  • Every reaction request is re-checked on the server: replay ids, rate limits, bucket and distance.

Not verified in-game

Version 1.1.0 has never run on a live server. The plain-Lua specs load the real scripts and pass against stubbed natives. These still need a OneSync server with two clients:

  • Spawning, ownership migration, tasks and speech with real natives.
  • The server-side natives used when a networked ped is created (outfit, props, weapon, armour). The controlling client applies the same values again.
  • State bags reaching clients that receive the entity later.
  • Blocking exports across resources; the callback form is there if the runtime refuses to yield.
  • Native argument lists for patrol, wander, guard, scenario blocking areas and population density.
  • That clearing an area leaves the handler's own peds alone.
  • The np_hud, ox_target and qb-target provider calls with several options, and the arrow keys for shared keys.
  • Whether re-applying the look after an ownership change shows as a twitch.
  • Cloning a player ped, and copying the clone into a networked ped.

Set it up

Compatibility

Nothing is a dependency. Everything below is detected at runtime and used when it runs.

KindSupported
Frameworkes_extended first, then qbx_core or qb-core, for job and gang conditions. Standalone works
Interactionnp_hud prompt, ox_target or qb-target, an optional built-in E-key text
ServerOneSync for networked NPCs
Staffnp_admin, or the console, np_admin_fallback identifiers and ESX groups. No ACE
NP DEV resourceWhat np_npchandler does with it
np_prophandlerHeld props go through it when it runs
np_hudThe interact prompt
np_adminThe np_npchandler.debug node and live settings for switches and budgets

Installation

No database, no NUI build.

  1. Put the folder in your resources as np_npchandler.
  2. Start it before the resources that use it:
    ensure np_npchandler
  3. Turn on OneSync if you use networked NPCs.
  4. Optional: np_prophandler for held props, np_hud, ox_target or qb-target for interaction, np_admin for permissions and live settings.
  5. Check the specs if you change it: luac -p on every file, then lua tests/*_spec.lua.

Used by the np_* resources

Every np_* resource with NPCs lists np_npchandler as a required dependency, with no fallback. It does their model loading, distance loop, ped flags and cleanup. Start it before them.

ResourceWhat goes through np_npchandler
np_bankingBranch tellers, addLocalNpc
np_characterThe select-screen preview peds, createLocalPed
np_clothingStore clerks as registerNpc, the hidden catalogue scan peds
np_dartsThe house regular, createLocalPed
np_drugsRehab doctors as addLocalNpc, the K9 dog as createNetworkedPed
np_environmentalScene peds and animals, the editor preview peds
np_farmingBuyers, pen animals, the animal on a lead and the crows
np_fishingThe fish buyer and tackle shop peds, registerNpcs
ResourceWhat goes through np_npchandler
np_gangsLester, the corner customers with walkTo and dismissPed, the trial's drivers, cops and gunmen
np_golfThe NPC caddie, createLocalPed
np_identificationDesk and forger NPCs with their interact option, hidden while a view is open
np_metal-scannerThe gate guard and the ground-find buyer
np_prisonNPC guards, post guards, the plug (only for inmates) and the intake bus driver
np_shopsThe shop clerks, registerNpc and playAnim
np_spy-pigeonThe body left behind as a clone of the player, the hawk

Exports

Server and client exports for registered and immediate peds, runtime control and population, plus lifecycle events.

-- client: only this player gets it
exports.np_npchandler:addLocalNpc({ id = 'np_drugs:rehab_doctor', model = 's_m_m_doctor_01',
  coords = c, scenario = 'WORLD_HUMAN_CLIPBOARD',
  interact = { label = 'Ask for help', icon = 'handshake-angle',
    event = 'np_drugs:rehab:open', distance = 2.5 } })

-- server: a guard everyone sees
exports.np_npchandler:registerNpc({
  id = 'np_prison:tower_guard', model = 's_m_m_prisguard_01', coords = vector4(...),
  mode = 'networked', weapon = 'WEAPON_CARBINERIFLE', guard = { radius = 6.0 }, routingBucket = 0,
})

-- lifecycle: register again after a restart (server and client)
AddEventHandler('np_npchandler:ready', registerAll)
AddEventHandler('np_npchandler:spawned', function(id, entity, data) end)
SideMain exports
ServerregisterNpc(s), updateNpc, removeNpc, setNpcEnabled, getNpcEntity, refreshPlayer, spawnNetworkedPed, redeemInteraction, getDiagnostics
ClientaddLocalNpc(s), removeLocalNpc, getNpcEntity, isNpcSpawned, createLocalPed, createNetworkedPed, setCanInteract, playAnim, walkTo, getDiagnostics

Questions

Has it run on a live server?

Not yet. Version 1.1.0 is covered by plain-Lua specs that load the real scripts against stubbed natives. Spawning, ownership migration, tasks, speech, the interaction providers, the population natives and state bag replication haven't been checked in game, so expect fixes in the first versions.

Is this something players see?

Only through the resources that use it. It has no UI. It is the place other scripts get their NPCs from, so the shopkeeper, the desk clerk or the guard is spawned, hidden and cleaned up the same way everywhere.

Do I need a framework?

No. ESX, qbx or qb are only used for jobs and gangs conditions, ESX first. Without one, NPCs without those conditions work as usual.

Can an NPC offer more than one option?

Yes. Since 1.1.0 interact takes a list of up to six options (buy, rob, search), each with its own key, event and jobs, gangs or hours. Options that share a key are picked with the arrow keys. A client predicate hides an option while the player can't use it.

Which np_* resources use it?

Every np_* resource with NPCs, from np_gangs and np_shops to np_prison and np_character, 15 in all. They list it as a required dependency and have no fallback of their own, so start it before them. The table under Set it up shows what each one sends through it.

What happens when my resource stops?

Every NPC it registered or created is removed with it, including preview and mission peds. Server mission peds with an ownerSource also go when that player drops.

Does it use ACE permissions?

No. npchandler_debug is gated by the np_admin node np_npchandler.debug. Without np_admin, the console, identifiers in np_admin_fallback and, on ESX, the groups in np_admin_fallback_groups.

Can I limit which models are allowed?

Yes. Registration is open by default; Config.NpcHandler.restrict takes lists of models, scenarios, anim dicts, weapons and roles.

Works well with

Register a ped once. Let the handler do the rest.

Usage by pattern, the definition, exports, events and configuration are in the docs.

np_npchandler docs