
Server API (C#)
Namespace Net.Server. Every public member is listed here.
Resource lifecycle
Each server resource assembly contains one class that derives from IResource or AsyncResource. Event handlers live in classes that implement IScript.
abstract class IResource
Entry point of a resource.
public sealed class Main : IResource
{
public override void OnStart() => Net.Log("started");
}
virtual void IResource.OnStart()
Called once after the assembly was loaded.
virtual void IResource.OnStop()
Called when the resource stops, including during reload or server shutdown.
virtual Task IResource.OnStartAsync()
Asynchronous variant used by the host. By default it calls OnStart.
virtual Task IResource.OnStopAsync()
Asynchronous variant used by the host. By default it calls OnStop.
virtual IPlayerFactory? IResource.GetPlayerFactory()
Return a factory to use your own player class.
virtual IVehicleFactory? IResource.GetVehicleFactory()
Return a factory to use your own vehicle class.
abstract class AsyncResource : IResource
Base class with Task OnStart() and Task OnStop() for asynchronous start and stop.
interface IScript
Marker interface for classes that contain handlers.
interface IPlayerFactory { IPlayer Create(PlayerHandle handle); }
Creates your player type once per connection.
public sealed class MyPlayer(PlayerHandle handle) : Player(handle) { public int Money; }
public sealed class Factory : IPlayerFactory
{
public IPlayer Create(PlayerHandle handle) => new MyPlayer(handle);
}
interface IVehicleFactory { IVehicle Create(VehicleHandle handle); }
Creates your vehicle type.
class Player(PlayerHandle handle) : IPlayer
Default player implementation and base class for your own.
class Vehicle(VehicleHandle handle) : IVehicle
Default vehicle implementation and base class for your own.
sealed class PlayerHandle
Identifies a connection. Id and Name are read-only.
sealed class VehicleHandle
Identifies a server vehicle. Id is read-only.
Events and commands
Handlers may be static or instance methods and return void or Task. After an ordinary await they continue on the server thread. Call the API only from that thread.
[ScriptEvent(ScriptEventType type)]
ScriptEventAttribute. Subscribes a method to a built-in event.
enum ScriptEventType
PlayerConnect, PlayerDisconnect, PlayerDeath, PlayerSpawn, PlayerEnterVehicle, PlayerLeaveVehicle, PlayerEnterColShape, PlayerLeaveColShape, PlayerDamage, PlayerWeaponChange.
PlayerConnect(IPlayer player)
A player joined. The first spawn happens after all connect handlers finished.
[ScriptEvent(ScriptEventType.PlayerConnect)]
public static void Connect(IPlayer player) => player.SetSyncedMetaData("kills", 0);
PlayerDisconnect(IPlayer player)
A player left. Setters throw after this point.
PlayerSpawn(IPlayer player, bool respawn)
A player spawned. respawn is false for the first spawn.
PlayerDeath(IPlayer player, IPlayer? killer, uint weapon)
A player died. killer is null without another player.
PlayerEnterVehicle(IPlayer player, IVehicle vehicle, int seat)
A player took a seat. The driver seat is -1.
PlayerLeaveVehicle(IPlayer player, IVehicle vehicle, int seat)
A player left a seat.
PlayerEnterColShape(IPlayer player, IColShape shape)
A player entered a collision shape. Checked ten times per second.
PlayerLeaveColShape(IPlayer player, IColShape shape)
A player left a collision shape.
PlayerDamage(IPlayer player, int before, int after)
Health went down. The value comes from the player's client.
PlayerWeaponChange(IPlayer player, uint oldWeapon, uint newWeapon)
The selected weapon changed.
[ClientEvent(string name)]
ClientEventAttribute. Handles net.emitServer(name, ...). The first parameter is the player, the rest are typed from the client arguments. Wrong types are logged and the call is skipped.
[ClientEvent("buy")]
public static void Buy(IPlayer player, string item, int amount = 1)
{
if (amount is < 1 or > 10) return; // never trust client data
}
[ClientRpc(string name)]
ClientRpcAttribute. Handles net.emitRpc(name, ...) and returns the result to the caller. May return a value, Task or Task<T>.
[ClientRpc("balance")]
public static int Balance(IPlayer player) =>
player.GetData<int>("money", out var money) ? money : 0;
[ServerEvent(string name)]
ServerEventAttribute. Handles Net.Emit(name, ...) from any server resource.
[Command(string name)]
CommandAttribute. Handles a command typed in the F8 console. Use (IPlayer player, string arg) for exactly one word or (IPlayer player, string[] args) for any argument count. Built-in client commands take precedence. Every player may run it.
[Command("heal")]
public static void Heal(IPlayer player, string[] args) => player.Health = 200;
Player
IPlayer
ushort Id { get; }
Server id of the connection.
string Name { get; }
Unique name. A duplicate joins as Name(2).
IVehicle? Vehicle { get; }
Current vehicle, or null.
uint Model { get; set; }
Ped model hash.
Position Position { get; set; }
World position.
Rotation Rotation { get; set; }
Rotation in degrees.
int Health { get; set; }
0 to 65535. A player is dead at 100 or below.
void Spawn(Position position)
Spawns the player at a position and keeps the rotation.
void Spawn(Position position, Rotation rotation)
Spawns with position and rotation.
void SendMessage(string message)
Shows a line in the player's console. At most 255 bytes.
void Kick(string reason)
Shows the reason and disconnects the player.
void GiveWeapon(string weapon, int ammo = 250)
Gives a weapon by GTA name. A respawn restores the server loadout.
player.GiveWeapon("weapon_carbinerifle", 120);
void RemoveAllWeapons()
Removes every weapon.
void AddWeaponComponent(uint weapon, uint component)
Configures a compatible GTA attachment for this weapon. It is also applied when the weapon is given later and shown to players who join later.
player.AddWeaponComponent(Net.Hash("weapon_pistol"), Net.Hash("component_at_pi_supp_02"));
void RemoveWeaponComponent(uint weapon, uint component)
Removes a server-configured attachment for the owner and observers.
bool HasWeaponComponent(uint weapon, uint component)
Whether this attachment is configured for the player on the server.
IReadOnlyList<uint> GetWeaponComponents(uint weapon)
Returns a snapshot of the configured component hashes. Removing the weapon also clears its attachments.
void Emit(string name, params object?[] args)
Calls net.onServer(name) on this player. Arguments are sent as JSON, at most 32,000 bytes.
void SetData(string key, object? value)
Stores a value on the server.
bool GetData<T>(string key, out T? value)
Reads a stored value of type T.
bool HasData(string key)
True if the key exists.
void DeleteData(string key)
Removes the key.
void SetSyncedMetaData(string key, object? value)
Stores a value every client script can read.
bool GetSyncedMetaData<T>(string key, out T? value)
Reads a synced value.
bool HasSyncedMetaData(string key)
True if the synced key exists.
void DeleteSyncedMetaData(string key)
Removes it on all clients.
Player state and appearance
Also part of IPlayer. State values are reported by the player's client.
int Armour { get; set; }
0 to 100.
int Ping { get; }
Round trip time in milliseconds.
uint CurrentWeapon { get; set; }
Selected weapon hash.
bool IsDead / IsAiming / IsInRagdoll { get; }
State flags.
bool IsSpawned { get; }
Whether this connection currently has a spawned player. Set a model before the first spawn.
bool IsInCover / IsSwimming / IsReloading { get; }
State flags.
int Seat { get; }
Seat in the current vehicle, -1 for the driver, -2 on foot.
bool Frozen { get; set; }
Freezes the player. Applied on the player's own client.
bool Invincible { get; set; }
Makes the player invincible. Applied on the player's own client.
bool Visible { get; set; }
Visibility for everyone.
void SetClothes(int component, int drawable, int texture = 0, int palette = 0)
Clothing component 0 to 11, kept for players who join later.
player.SetClothes(11, 15, 2);
void SetProp(int prop, int drawable, int texture = 0)
Hat, glasses and other props, 0 to 7.
void ClearProp(int prop)
Removes a prop.
void PlayAnimation(string dictionary, string name, int flag = 0, int duration = -1, float blendIn = 8f, float blendOut = -8f)
Plays an animation on the player.
void StopAnimation()
Clears the player's tasks.
void SetIntoVehicle(IVehicle vehicle, int seat = -1)
Puts the player into a seat.
void SetAmmo(string weapon, int ammo)
Sets the ammunition of a weapon.
void RemoveWeapon(string weapon)
Removes one weapon.
void SetWeather(string weather)
Weather for this player only, for example "RAIN".
void SetTime(int hour, int minute = 0)
Clock for this player only.
Task<T?> CallRpc<T>(string name, params object?[] args)
Asks the client (net.onRpc) and waits for the answer. Fails after 10 seconds.
var seen = await player.CallRpc<bool>("isMenuOpen");
Vehicle
IVehicle. Create with Net.CreateVehicle.
ushort Id { get; }
Vehicle id.
uint Model { get; }
Model hash.
Position Position { get; set; }
Setting it moves the vehicle and stops its linear velocity.
Rotation Rotation { get; set; }
Rotation in degrees.
int PrimaryColor { get; set; }
GTA colour index 0 to 159.
int SecondaryColor { get; set; }
GTA colour index 0 to 159.
bool EngineOn { get; set; }
Once set by a script, the value stays across driver changes.
string NumberPlate { get; set; }
At most 8 ASCII characters. Empty until a script sets it.
bool Locked { get; set; }
Locks the doors.
int Livery { get; set; }
Livery index, -1 until set.
float DirtLevel { get; set; }
0 to 15.
SetMod(int or VehicleModType type, int index) / GetMod(type)
Configures and reads a GTA mod slot. Index -1 restores stock. Use SetWheels for slots 23 and 24.
SetToggleMod(type, bool enabled) / GetToggleMod(type)
Sets or reads a toggle in slots 17 to 22, including turbo and xenon headlights. Accepts an integer or VehicleModType.
SetWheels(int wheelType, int frontIndex, int? rearIndex = null, bool customTires = false, bool? rearCustomTires = null) / GetWheels()
Wheel family, front/rear indices and tire variants. The rear inherits omitted values from the front. GetWheels returns null until configured. WheelType and HasCustomTires(slot) read individual values.
SetXenon(bool left, bool right, bool front, bool back) / GetXenon()
Configures and reads the four underbody lights.
SetXenonColor(byte r, byte g, byte b) / GetXenonColor()
Configures underbody RGB. Colour getters return a nullable Rgba.
SetExtra(int extra, bool enabled) / GetExtra(int extra)
Model-specific vehicle extras. Returns null until configured.
SetTireSmokeColor(byte r, byte g, byte b) / GetTireSmokeColor()
RGB colour for the tire smoke toggle.
SetPaintFinish(int primary, int secondary) / GetPaintFinish()
Primary and secondary paint finishes.
SetCustomPrimaryColor(r, g, b) / GetCustomPrimaryColor() / ClearCustomPrimaryColor()
Overrides the primary palette colour with RGB or restores it.
SetCustomSecondaryColor(r, g, b) / GetCustomSecondaryColor() / ClearCustomSecondaryColor()
Overrides the secondary palette colour with RGB or restores it.
SetExtraColors(int pearlescent, int wheels) / GetExtraColors()
Pearlescent and wheel palette indices.
SetInteriorColors(int trim, int dashboard) / GetInteriorColors()
Interior trim and dashboard palette indices.
ModKit, WindowTint, PlateStyle, RoofLivery, HeadlightColor
Integer properties with getters and setters. HeadlightColor controls headlights independently of underglow.
BulletproofTires, DriftTires
Boolean properties with getters and setters.
void Repair()
Repairs the vehicle.
IPlayer? Driver { get; }
The driver, or null.
IReadOnlyList<IPlayer> Passengers { get; }
Passengers ordered by seat.
void SetData(string key, object? value)
Stores a value on the server.
bool GetData<T>(string key, out T? value)
Reads it.
bool HasData(string key)
True if the key exists.
void DeleteData(string key)
Removes it.
void Destroy()
Removes the vehicle for everyone.
Blips and markers
Visible to all players, including those who join later.
IBlip Net.CreateBlip(Position position, int sprite = 1, int color = 0, string name = "", float scale = 1f)
Creates a map blip.
var blip = Net.CreateBlip(new(100, 200, 30), sprite: 40, color: 2, name: "Garage");
IMarker Net.CreateMarker(int type, Position position, float scale = 1f, Rgba? color = null)
Creates a world marker, drawn within 200 m. Types 0 to 43.
IBlip: uint Id, Position, int Sprite, int Color, float Scale, string Name
All properties except Id can be changed.
void IBlip.Destroy()
Removes the blip.
IMarker: uint Id, Position, int Type, float Scale, Rgba Color
All properties except Id can be changed.
void IMarker.Destroy()
Removes the marker.
Collision shapes and checkpoints
IColShape. Evaluated on the server.
IColShape Net.CreateColShapeSphere(Position position, float radius)
Sphere.
var shop = Net.CreateColShapeSphere(new(25, -1347, 29), 3f);
IColShape Net.CreateColShapeCylinder(Position position, float radius, float height)
Cylinder standing on the position.
IColShape Net.CreateColShapeCuboid(Position first, Position second)
Box between two corners.
ICheckpoint Net.CreateCheckpoint(Position position, float radius, int markerType = 1, Rgba? color = null)
Cylinder-like trigger with a visible marker.
IColShape: uint Id, Position, IReadOnlyList<IPlayer> Players
Id, position (writable) and the players inside.
bool IColShape.Contains(Position position)
Point test.
void IColShape.SetData / bool GetData<T>
Values attached to the shape.
void IColShape.Destroy()
Removes the shape.
interface ICheckpoint : IColShape
Adds IMarker Marker { get; }.
Dimensions and personal items
Players only see players, vehicles, objects and collision shapes of their own dimension. The default is 0.
int IPlayer.Dimension { get; set; }
Moves the player to another world.
int IVehicle.Dimension { get; set; }
Same for a vehicle.
int IColShape.Dimension { get; set; }
A shape only reacts to players in its dimension.
IBlip IPlayer.CreateBlip(Position position, int sprite = 1, int color = 0, string name = "", float scale = 1f)
A blip only this player sees. Removed when the player leaves.
IMarker IPlayer.CreateMarker(int type, Position position, float scale = 1f, Rgba? color = null)
A marker only this player sees.
Objects and peds
IWorldObject and IServerPed. Each client creates them locally, so physics and NPC behaviour are not synchronised.
IWorldObject Net.CreateObject(string model, Position position, float heading = 0, int dimension = 0)
Places an object, also by hash.
var cone = Net.CreateObject("prop_roadcone02a", player.Position);
IServerPed Net.CreatePed(string model, Position position, float heading = 0, int dimension = 0)
A standing, invincible character.
IReadOnlyList<IWorldObject> Net.Objects
All objects and peds.
interface IWorldObject: Id, Model, Position, Heading, Dimension, Frozen
Position, heading, dimension and frozen can be changed.
interface IServerPed : IWorldObject
A ped.
void AttachTo(IPlayer player, int bone = 0, Position offset = default, Rotation rotation = default)
Attaches to a ped bone, 57005 is the right hand.
void AttachTo(IVehicle vehicle, int bone = 0, Position offset = default, Rotation rotation = default)
Attaches to a vehicle.
void Detach()
Releases it at its stored position.
void SetData / bool GetData<T> / void Destroy()
Server data and removal.
Vehicle data and condition
Also part of IVehicle.
float EngineHealth / BodyHealth { get; }
1000 is undamaged. Reported by the driver's client.
bool IsDestroyed { get; }
True for a wreck.
void SetSyncedMetaData(string key, object? value)
Value every client script can read.
bool GetSyncedMetaData<T> / bool HasSyncedMetaData / void DeleteSyncedMetaData
Read, test and remove.
Stream-synced data
Only clients that currently have the player or vehicle receive it. Available on IPlayer and IVehicle.
void SetStreamSyncedMetaData(string key, object? value)
Sets a value.
bool GetStreamSyncedMetaData<T> / bool HasStreamSyncedMetaData / void DeleteStreamSyncedMetaData
Read, test and remove.
Damage, explosions, scenes and moving peds
Moving peds are calculated by the nearest player and followed by the others, so they are only roughly in step.
float IVehicle.EngineHealth / BodyHealth { get; set; }
Setting them damages or repairs the vehicle.
void IVehicle.Explode()
Blows the vehicle up.
void Net.CreateExplosion(Position position, int type = 0, float damageScale = 1f, int dimension = 0)
An explosion in one dimension.
void IServerPed.GoTo(Position target, float speed = 1f)
Walks or runs there.
void IServerPed.Wander() / StopMoving()
Walks around, or stops.
IPlayer? IServerPed.Controller { get; }
Who currently calculates the ped.
void Net.PlaySyncedScene(Position position, Rotation rotation, IReadOnlyList<SceneActor> actors, int dimension = 0)
Animations of players and server peds around one origin.
Net.PlaySyncedScene(spot, default, [new SceneActor(player, dict, "a"), new SceneActor(npc, dict, "b")]);
sealed class SceneActor(IPlayer or IServerPed, string dictionary, string animation)
Dictionary and Animation are read-only.
Voice chat
Needs a [voice] table in server.toml. Players of the same dimension within [voice] range hear each other, quieter with distance.
bool IPlayer.VoiceMuted { get; set; }
Nobody hears a muted player.
IVoiceChannel Net.CreateVoiceChannel()
Members hear each other everywhere, like a radio or phone.
var radio = Net.CreateVoiceChannel();
radio.Add(player);
interface IVoiceChannel: Id, Players
Id and members.
void IVoiceChannel.Add(IPlayer) / Remove(IPlayer) / Destroy()
Manage members.
Virtual entities
A position with data and no model. Every client of the dimension receives it and is told when it is in range, so do not put secrets into it.
IVirtualEntity Net.CreateVirtualEntity(Position position, float streamingDistance, int dimension = 0)
Creates one.
var kiosk = Net.CreateVirtualEntity(new(25, -1347, 29), 30f);
kiosk.SetData("name", "Kiosk");
interface IVirtualEntity: Id, Position, StreamingDistance, Dimension
Position and dimension can be changed.
void SetData / bool GetData<T> / bool HasData / void DeleteData / void Destroy
Synchronised data and removal.
Map and interiors
Applied for everyone, including players who join later.
void Net.RequestIpl(string name) / void Net.RemoveIpl(string name)
Loads or removes an optional map part.
void Net.SetInteriorEntitySet(Position interior, string entitySet, bool active)
Switches an entity set of the interior at that position.
Connection queue
With connectionQueue = true in server.toml a script decides who may join. The client waits meanwhile.
ConnectionQueueAdd(IConnectionInfo info) / ConnectionQueueRemove(IConnectionInfo info)
ScriptEventType values. Remove fires when a waiting client gives up.
[ScriptEvent(ScriptEventType.ConnectionQueueAdd)]
public static void Add(IConnectionInfo info) => info.Accept();
interface IConnectionInfo: Id, Name, Ip
Who is waiting.
void IConnectionInfo.Accept() / Decline(string reason)
Lets the client in or rejects it.
Restarting
void Net.StartResource(string name)
Queues a resource start for the next server tick. Its dependencies must already be running.
void Net.StopResource(string name)
Queues a resource stop. Its objects are removed and its pending RPCs are cancelled.
void Net.RestartResource(string name)
Queues a reload of the C# DLL and client files. Objects from the old instance are removed, connected players receive the replacement client package and the new instance receives their connect events.
Between resources
List the other resource under deps in resource.toml.
string Net.ResourceName
Name of the calling resource.
void Net.Export(string name, Delegate function)
Offers a function. Use .NET and netMP types in its signature.
Net.Export("balance", new Func<IPlayer, int>(Bank.Balance));
T Net.Import<T>(string resource, string name)
Gets an exported function.
var balance = Net.Import<Func<IPlayer, int>>("bank", "balance");
World and timers
void Net.SetWeather(string weather)
Weather for everyone, including later joiners.
void Net.SetTime(int hour, int minute = 0)
Clock for everyone.
IReadOnlyList<IVehicle> Net.Vehicles
All server vehicles.
IVehicle? Net.GetVehicle(ushort id)
Vehicle by id.
int Net.SetTimeout(Action action, int milliseconds)
Runs once on the server thread.
int Net.SetInterval(Action action, int milliseconds)
Runs repeatedly on the server thread.
void Net.ClearTimer(int id)
Stops a timer.
Game data
Read-only, case-insensitive catalogs from the server's data directory for GTA V Legacy build 3889. Model catalogs contain a starter set; scripts may also use other valid model hashes.
GameData.Clothes
Clothing component names and slot indices.
var shoes = GameData.Clothes["shoes"];
GameData.PedModels
Ped model names and their GTA hashes.
GameData.VehicleModels
Vehicle model names and hashes.
uint model = GameData.VehicleModels["sultan"];
GameData.VehicleMods
Tuning slot names and indices from 0 to 49.
GameData.WeaponModels
Weapon names and GTA hashes.
GameData.RpfData
Relative base-game archive paths and their JOAAT path hashes.
Net
Static entry point.
void Net.Log(string message)
Writes to the server log.
void Net.Broadcast(string message)
Shows a console line to every player.
CancellationToken Net.Stopping
Cancelled when the server shuts down.
IReadOnlyList<IPlayer> Net.Players
All connected players, ordered by id.
IPlayer? Net.GetPlayer(ushort id)
Player by id.
IPlayer? Net.GetPlayer(string name)
Player by name, ignoring case.
uint Net.Hash(string name)
joaat hash of a model or weapon name.
IVehicle Net.CreateVehicle(VehicleModel model, Position position, Rotation rotation)
Creates a vehicle using a free network ID. Destroying a vehicle frees its ID for reuse.
IVehicle Net.CreateVehicle(string model, Position position, Rotation rotation)
Same, by model name.
var car = Net.CreateVehicle("sultan", player.Position, player.Rotation);
IVehicle Net.CreateVehicle(uint model, Position position, Rotation rotation)
Same, by hash.
void Net.Emit(string name, params object?[] args)
Raises [ServerEvent(name)] in all resources.
void Net.EmitAllClients(string name, params object?[] args)
Calls net.onServer(name) on every player.
void Net.SetSyncedMetaData(string key, object? value)
Global value readable by all clients.
bool Net.GetSyncedMetaData<T>(string key, out T? value)
Reads a global value.
bool Net.HasSyncedMetaData(string key)
True if the key exists.
void Net.DeleteSyncedMetaData(string key)
Removes the global value.
Types
Value types.
record struct Position(float X, float Y, float Z)
World coordinates.
record struct Rotation(float X, float Y, float Z)
Pitch, roll and heading in degrees.
record struct Rgba(byte R, byte G, byte B, byte A = 255)
Colour.
enum PedModel
FreeModeMale01, FreeModeFemale01.
enum VehicleModel
Adder, Sultan. Any other model works by name or hash.