Getting started with scripting for FiveM might be overwhelming. In this guide, we’ll show you how to get started with a C# resource that implements a car spawner command.
When you set up your C# project, you will have two projects: MyResourceNameClient and MyResourceNameServer.
Any C# class that handles FiveM scripting events must inherit from the BaseScript class:
using CitizenFX.Core;
namespace MyResourceNameClient
{
public class Class1 : BaseScript
{
public Class1()
{
}
}
}using System;
using System.Collections.Generic;
using CitizenFX.Core;
using static CitizenFX.Core.Native.API;
namespace MyResourceNameClient
{
public class Class1 : BaseScript
{
public Class1()
{
EventHandlers["onClientResourceStart"] += new Action<string>(OnClientResourceStart);
}
private void OnClientResourceStart(string resourceName)
{
if (GetCurrentResourceName() != resourceName) return;
RegisterCommand("car", new Action<int, List<object>, string>((source, args, raw) =>
{
TriggerEvent("chat:addMessage", new
{
color = new[] {255, 0, 0},
args = new[] {"[CarSpawner]", $"I wish I could spawn this {(args.Count > 0 ? $"{args[0]} or" : "")} adder but my owner was too lazy. :("}
});
}), false);
}
}
}RegisterCommand("car", new Action<int, List<object>, string>(async (source, args, raw) =>
{
var model = "adder";
if (args.Count > 0)
{
model = args[0].ToString();
}
var hash = (uint) GetHashKey(model);
if (!IsModelInCdimage(hash) || !IsModelAVehicle(hash))
{
TriggerEvent("chat:addMessage", new
{
color = new[] { 255, 0, 0 },
args = new[] { "[CarSpawner]", $"It might have been a good thing that you tried to spawn a {model}." }
});
return;
}
var vehicle = await World.CreateVehicle(model, Game.PlayerPed.Position, Game.PlayerPed.Heading);
Game.PlayerPed.SetIntoVehicle(vehicle, VehicleSeat.Driver);
TriggerEvent("chat:addMessage", new
{
color = new[] {255, 0, 0},
args = new[] {"[CarSpawner]", $"Woohoo! Enjoy your new ^*{model}!"}
});
}), false);To ensure Mono can load debug symbols and display full debug information:
EmbeddedFor server-side scripting, you’ll want to use the server project in your C# solution.