Scripting/Server/NPCs

An NPC is a pedestrian controlled by your script. An NPC handle is a Player instance, so every Player property and method works on it, plus the NPC-only members below. The ped is a real world ped driven by real game opcodes, so walking, pathing, animations, aiming and shooting are native game behaviour.

Creating, finding and removing

CallNotes
CreateNPC(skin, Vector(x,y,z), angle)Returns the NPC handle or null. Angle in degrees (0 = +X, 90 = +Y).
CreateNPC(skin, x, y, z, angle)Same with flat arguments.
FindNPC(id)id is npc.NPCID (0-63) or npc.ID (the entity slot).
DestroyNPC(npc) / npc.Remove()Remove it everywhere; frees the slot.
npc.Respawn()Back to the creation spot, full health, idle. Fires onNPCRespawn.

skin is 0-300 (200-299 are the custom skins from <skin> in Script.xml). Skin 0 is always safe. An unloaded model falls back to ped 0 and switches when it loads. The pool holds 64 NPCs; CreateNPC returns null when full.

NPC members

PropertyTypeAccessDescription
NPCIDintegerr0-based NPC index that FindNPC takes.
IDintegerrEntity slot (255 and up). Same field that player.ID uses.
IsNPCbooleanrAlways true.
Skin / Health / Armourint / float / floatrwHealth and armour 0-100. Damage from the world is reported back and tracked.
Pos / AngleVector / floatrwReading gives the live reported position. Writing teleports.
WeaponintegerrwAssigning gives the weapon with 0 ammo, and a gun with 0 rounds cannot fire (an attack objective turns into a punch). Always use npc.SetWeapon(id, ammo) instead.
ImmunebooleanrwSee the caveat below.
ObjectiveintegerrwCurrent objective (OBJ_*).
VehicleVehicle|nullrwAssign a vehicle to seat the NPC as driver; null to step out.
VehicleSeatintegerrw0 driver, 1-8 passenger, -1 out.
ObjectiveArgumentBehaviour
OBJ_IDLE(none)Stand on foot.
OBJ_WALK_TOVectorWalk to the point.
OBJ_RUN_TOVectorRun to the point.
OBJ_ATTACK_PLAYERplayerAttack that player (needs a weapon with ammo).
OBJ_FOLLOW_PLAYERplayerFollow that player.
OBJ_DRIVE_TOuse DriveTo()Drive a car to a point.
Carefulnpc.Immune is enforced by pinning health to the server value each frame and forcing the ped back to idle. An immune NPC will not die and will not stay on the ground, but it can still visibly stagger from explosions or shotgun blasts. It is not engine-level invincibility.
local guard = CreateNPC(0, Vector(812.0, -935.0, 36.0), 90.0);
guard.SetWeapon(WEP_AK47, 500);         // a weapon with ammo (weapon ids 0-12)
guard.SetObjective(OBJ_ATTACK_PLAYER, FindPlayer(0));

function onNPCDeath(npc, killerPlayerId)
{
    if (killerPlayerId >= 0) Message(FindPlayer(killerPlayerId).Name + " took out a guard");
    NewTimer("RespawnNpc", 5000, 1, npc);
}
function RespawnNpc(npc) { npc.Respawn(); }
Categories: NPCs