NPCs

NPCs are non playable characters and in GTA V scripting they are called Ped. Peds are a game entity like Prop or Vehicle and can be created, moved, assigned different model textures, equipped with weapons and controlled through different tasks.


Spawn a new NPC

A GTA V Ped can be created by the World.CreatePed function. This takes two parameters: an ID to assign the 3D model and textures, and the location where the Ped is created.

The model IDs are the same you used for changing your character’s appearance to a cat. A list of all available models can be found here. PedHash.Cat, PedHash.Deer, PedHash.AviSchwartzman are all possible IDs you can assign to the NPC you want to create. You can create a new model variable, which you will name myPedModel and assign it a model ID:

Model myPedModel = PedHash.AviSchwartzman;

The location where the NPC is created through a vector3 data type, which represents a vector in 3D space. This basically means a point that contains X, Y and Z coordinates. You can give absolute coordinates, making the Ped appear at a specific location in the game, but you can also use a location relative to your position in the game. In order not to risk making a Ped appear somewhere completely outside of your view – on some mountain or in the sea – you can point to a relative position in front of the player.

You want to establish the player with Game.Player.Character, followed by a function that retrieves the player position within the game world. That’s called by using GetOffsetPosition, which takes a Vector3. The values of the X, Y and Z of the Vector3 offset the location based on the origin point represented by the player. Therefore, you can move the place where you want the Ped to appear by adding values to the X axis (left or right of player), Y axis (ahead or behind the player), and Z axis (above or below the player). To make a Ped appear in front of the player you can create a Vector3 data type with 0 for X, 5 for Y and 0 for Z: new Vector3(0, 5, 0). Let’s make a Vector3 variable, which you will name myPedSpawnPosition, assign it the values above for X, Y and Z coordinates from the player position:

Vector3 myPedSpawnPosition = Game.Player.Character.GetOffsetPosition(new Vector3(0, 5, 0));

Now you can use the model and the position variables to spawn the NPC in front of the player. Create a Ped variable named "myPed1" and use the World.CreatePed function to create an NPC with the Model variable "myPedModel", spawning at the location specified in the Vector3 variable "myPedSpawnPosition":

Ped myPed1 = World.CreatePed(myPedModel, myPedSpawnPosition); 
Example code
using System;
using System.Windows.Forms;
using GTA;
using GTA.Math;
using GTA.Native;

namespace moddingTutorial
{
    public class moddingTutorial : Script
    {
        public moddingTutorial()
        {
            this.Tick += onTick;
            this.KeyUp += onKeyUp;
            this.KeyDown += onKeyDown;
        }

        private void onTick(object sender, EventArgs e) //this function gets executed continuously 
        {
        }

        private void onKeyUp(object sender, KeyEventArgs e)//everything inside here is executed only when you release a key
        {
        }

        private void onKeyDown(object sender, KeyEventArgs e) //everything inside here is executed only when you press a key
        {
            //when pressing 'K'
            if(e.KeyCode == Keys.K)
            {
                //select a model and store it in a variable
                Model myPedModel = PedHash.AviSchwartzman;

                //create a position relative to the player
                Vector3 myPedSpawnPosition = Game.Player.Character.GetOffsetPosition(new Vector3(0, 5, 0));

                //create a Ped with the chosen model, spawning at the chosen position
                Ped myPed1 = World.CreatePed(myPedModel, myPedSpawnPosition); 
            }
        }
    }
}


Control Multiple NPCs

You can create multiple NPCs and give them custom names. Let’s create a human NPC and a cat NPC and call them "Jim" and "MannyTheCat" respectively:
Ped Jim = World.CreatePed(PedHash.AviSchwartzman, Game.Player.Character.GetOffsetPosition(new Vector3(0, 5, 0)));
Ped MannyTheCat = World.CreatePed(PedHash.Cat, Game.Player.Character.GetOffsetPosition(new Vector3(0, 3, 0)));

Try to kill one of the Ped NPCs you created by using the Kill().

Jim.Kill();

Note that when you kill your Ped "Jim", it falls on the floor and it won’t actually respond to any call or task you will give it, but it’s not removed from the game. To remove a specific Ped you have to use the Delete function, which will remove that instance (and will make the NPC disappear).

Jim.Delete();

To handle groups of NPCs you can use the List class. A List is a collection of objects, and a List of Peds allows us to store your NPCs. You can use an index to retrieve and control specific Peds in the group. You can see the reference for more detailed information. List is not included in System, so make sure you add “using System.Collections.Generic;” at the very top of your code, to link this namespace into your project.

Create a List of Peds named "myPeds" as a global variable inside public class moddingTutorial : Script:

List<Ped> myPeds = new List<Ped>();

Inside the onKeyDown function create five new Peds with a For Loop:

for (int i = 0; i < 5; i++) //loop 5 times
{
    //spawn a new Ped called newPed
    Ped newPed = World.CreatePed(PedHash.Clown01SMY, Game.Player.Character.GetOffsetInWorldCoords(new Vector3(i-2.5f, 8, 0)));
    //add the new Ped to my list of Peds myPeds
    myPeds.Add(newPed);
}

Now all the five Peds are part of the "myPeds" List. You can control each Ped individually by calling their individual number ID in the group. The first spawned Ped is myPed[0], the last one is myPeds[4].

Tell the 1st spawned NPC to start wandering around:

myPeds[0].Task.WanderAround();

Kill the 2nd spawned NPC:

myPeds[1].Kill();

Tell the 3rd NPC to jump:

myPeds[2].Task.Jump();

Tell the 4th NPC to walk toward the camera:

myPeds[3].Task.GoTo(GameplayCamera.Position);

Tell the 5th NPC to put their hands up for 3 seconds:

myPeds[4].Task.HandsUp(3000);


Assigning Tasks to NPCs

A Ped can be given a task using the Task function, just like you did in the previous tutorial for the player character.

myPed1.Task.WanderAround();

Some tasks involve interacting with other characters (Peds or Game.Player.Character) or take different parameters like positions (Vector3), duration (in milliseconds), and other data types.

You can give your NPC the task to fight against the player by using the FightAgainst function, which requires a target Ped parameter – which in the case of the player is expressed as Game.Player.Character.

myPed1.Task.FightAgainst(Game.Player.Character); //give npc task to fight against player

Try to replace the task to “fight against” with “flee from (player)” , “hands up”, “jump”… or some of the other available tasks.

See the TaskInvoker list for possible tasks, or click on the list of available tasks below.

List of available tasks
void AchieveHeading (float heading, int timeout=0)

void AimAt (Entity target, int duration)

void AimAt (Vector3 target, int duration)

void Arrest (Ped ped)

void ChatTo (Ped ped)

void Jump ()

void Climb ()

void ClimbLadder ()

void Cower (int duration)

void ChaseWithGroundVehicle (Ped target)

void ChaseWithHelicopter (Ped target, Vector3 offset)

void ChaseWithPlane (Ped target, Vector3 offset)

void CruiseWithVehicle (Vehicle vehicle, float speed, DrivingStyle style=DrivingStyle.Normal)

void DriveTo (Vehicle vehicle, Vector3 target, float radius, float speed, DrivingStyle style=DrivingStyle.Normal)

void EnterAnyVehicle (VehicleSeat seat=VehicleSeat.Any, int timeout=-1, float speed=1f, EnterVehicleFlags flag=EnterVehicleFlags.None)

void EnterVehicle (Vehicle vehicle, VehicleSeat seat=VehicleSeat.Any, int timeout=-1, float speed=1f, EnterVehicleFlags flag=EnterVehicleFlags.None)

void FightAgainst (Ped target)

void FightAgainst (Ped target, int duration)

void FightAgainstHatedTargets (float radius)

void FightAgainstHatedTargets (float radius, int duration)

void FleeFrom (Ped ped, int duration=-1)

void FleeFrom (Vector3 position, int duration=-1)

void FollowPointRoute (params Vector3[] points)

void FollowPointRoute (float movementSpeed, params Vector3[] points)

void FollowToOffsetFromEntity (Entity target, Vector3 offset, float movementSpeed, int timeout=-1, float distanceToFollow=10f, bool persistFollowing=true)

void GoTo (Entity target, Vector3 offset=default(Vector3), int timeout=-1)

void GoTo (Vector3 position, int timeout=-1)

void GoStraightTo (Vector3 position, int timeout=-1, float targetHeading=0f, float distanceToSlide=0f)

void GuardCurrentPosition ()

void HandsUp (int duration)

void LandPlane (Vector3 startPosition, Vector3 touchdownPosition, Vehicle plane=null)

void LeaveVehicle (LeaveVehicleFlags flags=LeaveVehicleFlags.None)

void LeaveVehicle (Vehicle vehicle, bool closeDoor)

void LeaveVehicle (Vehicle vehicle, LeaveVehicleFlags flags)

void LookAt (Entity target, int duration=-1)

void LookAt (Vector3 position, int duration=-1)

void ParachuteTo (Vector3 position)

void ParkVehicle (Vehicle vehicle, Vector3 position, float heading, float radius=20.0f, bool keepEngineOn=false)

void PerformSequence (TaskSequence sequence)

void PlayAnimation (string animDict, string animName)

void PlayAnimation (string animDict, string animName, float speed, int duration, float playbackRate)

void PlayAnimation (string animDict, string animName, float blendInSpeed, int duration, AnimationFlags flags)

void PlayAnimation (string animDict, string animName, float blendInSpeed, float blendOutSpeed, int duration, AnimationFlags flags, float playbackRate)

void RappelFromHelicopter ()

void ReactAndFlee (Ped ped)

void ReloadWeapon ()

void RunTo (Vector3 position, bool ignorePaths=false, int timeout=-1)

void ShootAt (Ped target, int duration=-1, FiringPattern pattern=FiringPattern.Default)

void ShootAt (Vector3 position, int duration=-1, FiringPattern pattern=FiringPattern.Default)

void ShuffleToNextVehicleSeat (Vehicle vehicle=null)

void Skydive ()

void SlideTo (Vector3 position, float heading)

void StandStill (int duration)

void StartScenario (string name, float heading)

void StartScenario (string name, Vector3 position, float heading)

void SwapWeapon ()

void TurnTo (Entity target, int duration=-1)

void TurnTo (Vector3 position, int duration=-1)

void UseParachute ()

void UseMobilePhone ()

void UseMobilePhone (int duration)

void PutAwayParachute ()

void PutAwayMobilePhone ()

void VehicleChase (Ped target)

void VehicleShootAtPed (Ped target)

void Wait (int duration)

void WanderAround ()

void WanderAround (Vector3 position, float radius)

void WarpIntoVehicle (Vehicle vehicle, VehicleSeat seat)

void WarpOutOfVehicle (Vehicle vehicle)

void ClearAll ()

void ClearAllImmediately ()

void ClearLookAt ()

void ClearSecondary ()

void ClearAnimation (string animSet, string animName)

You can spawn a group of NPCs and give them individual tasks. You can also make them interact with each other (or with the player character). Here you spawn three NPCs and tell them to fight with each other.

First create a List to store your Peds and a List to store the models of the Peds inside public class moddingTutorial : Script:

//create a list of Peds
List<Ped> myPeds = new List<Ped>();

//create a list of Ped models 
List<Model> myPedModel = new List<Model>();

Then in your onKeyDown function, add the models to the list of models, spawn them through a for loop, and give each individual Ped the task to fight one of the other two Peds.

//manually add models for each ped
myPedModel.Add(PedHash.Clown01SMY);
myPedModel.Add(PedHash.Doctor01SMM);
myPedModel.Add(PedHash.Abigail);


for(int i = 0; i < myPedModel.Count; i++)
{
    //spawn a new Ped for each model
    var newPed = World.CreatePed(myPedModel[i], Game.Player.Character.GetOffsetPosition(new Vector3(i*2, 3, 0)));
    //add the new Ped to my list of Peds
    myPeds.Add(newPed);
}

myPeds[0].Task.FightAgainst(myPeds[1]);
myPeds[1].Task.FightAgainst(myPeds[2]);
myPeds[2].Task.FightAgainst(myPeds[0]);

To clear a task at any given moment you can use the task ClearAllImmediately();. To stop your three NPCs from fighting each other, you give them the task to stop everything they are doing immediately.

myPeds[0].Task.ClearAllImmediately();
myPeds[1].Task.ClearAllImmediately();
myPeds[2].Task.ClearAllImmediately();

Peace is restored in the universe. To remove the NPCs use Delete().

myPeds[0].Delete();
myPeds[1].Delete();
myPeds[2].Delete();