Skip to Content
ScriptingFirst Resources by LanguageYour First FiveM C# Resource: Build, Spawn and Debug
Report an error
Open in ChatGPTOpen in Claude

Build a C# resource with a bounded vehicle command

This project targets the Legacy CitizenFX client runtime using the same pinned assembly version as the compiled interoperability lab. It is not an Enhanced .NET certification. The official C# starter  covers commands, native wrappers, a vehicle spawner and debug symbols; the complete project below makes loading, failure and teardown explicit.

Use a private development server where you can already connect and spawn. Install an appropriate .NET SDK for compiling this SDK-style project; the reference-assemblies package supplies the .NET Framework compile-time surface. Having a modern SDK installed does not change the in-game target runtime.

Create the client project

Create Client/Client.csproj in a working directory outside the live resource folder:

<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>net452</TargetFramework> <AssemblyName>Docs.First.Client.net</AssemblyName> <LangVersion>8.0</LangVersion> <DebugType>embedded</DebugType> <CopyLocalLockFileAssemblies>false</CopyLocalLockFileAssemblies> </PropertyGroup> <ItemGroup> <PackageReference Include="CitizenFX.Core.Client" Version="1.0.26803" ExcludeAssets="runtime" /> <PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies.net452" Version="1.0.3" PrivateAssets="all" /> </ItemGroup> </Project>

Do not copy CitizenFX.Core.Client.dll into the resource as a replacement for the platform’s runtime assembly. Keep client and server projects separate: changing the output filename does not turn a client API into a server API.

Add the complete script

Create Client/Client.cs. A BaseScript constructor registers commands and lifecycle handlers. The synchronous command delegate starts a task whose exceptions are handled inside the task; it does not use an unobserved async void command handler.

// example: first-csharp-client using System; using System.Collections.Generic; using System.Threading.Tasks; using CitizenFX.Core; using static CitizenFX.Core.Native.API; public sealed class FirstClient : BaseScript { private int vehicle; private int generation; private bool loading; public FirstClient() { RegisterCommand("docvehicle", new Action<int, List<object>, string>((source, args, raw) => { if (loading) return; var name = args.Count > 0 ? args[0]?.ToString() : "adder"; if (string.IsNullOrEmpty(name) || name.Length > 64) return; _ = SpawnAsync(name); }), false); RegisterCommand("docremove", new Action<int, List<object>, string>((source, args, raw) => { RemoveDemo(); }), false); EventHandlers["onResourceStop"] += new Action<string>((name) => { if (name != GetCurrentResourceName()) return; generation++; RemoveDemo(); }); } private void RemoveDemo() { if (vehicle != 0 && DoesEntityExist(vehicle)) DeleteEntity(ref vehicle); vehicle = 0; } private async Task SpawnAsync(string name) { var model = (uint)GetHashKey(name); if (!IsModelInCdimage(model) || !IsModelAVehicle(model)) { Debug.WriteLine("Choose a vehicle model available in this build."); return; } loading = true; var requestGeneration = generation; var startedAt = GetGameTimer(); try { RequestModel(model); while (!HasModelLoaded(model)) { if (generation != requestGeneration || unchecked((uint)(GetGameTimer() - startedAt)) >= 10000) { Debug.WriteLine("Model loading was cancelled or timed out."); return; } await Delay(50); } if (generation != requestGeneration) return; var ped = Game.PlayerPed; if (ped == null || !ped.Exists()) return; var position = ped.Position + ped.ForwardVector * 5.0f; RemoveDemo(); vehicle = CreateVehicle(model, position.X, position.Y, position.Z, ped.Heading, false, false); if (vehicle == 0 || !DoesEntityExist(vehicle)) { vehicle = 0; Debug.WriteLine("Vehicle creation failed."); return; } SetPedIntoVehicle(ped.Handle, vehicle, -1); Debug.WriteLine("Local demo created. Use docremove to delete it."); } catch (Exception error) { RemoveDemo(); Debug.WriteLine("Vehicle demo failed: " + error.GetType().Name); } finally { SetModelAsNoLongerNeeded(model); loading = false; } } }

The example owns one non-networked, client-local vehicle. The server has not authorized a purchase or created a persistent vehicle record. Do not deploy this demonstration as an unrestricted production command or use it to circumvent an entity-lockdown policy.

GetHashKey returns the model identifier; the C# native wrappers here require an unsigned model hash. The model is requested and released using that same value. Coordinates are read after loading, and a failed creation is checked before seating the player. The unsigned elapsed-time calculation handles the 32-bit game timer wrapping during the short loading deadline.

World.CreateVehicle is a higher-level asynchronous client wrapper used by the official example. Its result still needs a null/existence check. This example uses the underlying native sequence to make its ten-second bound and non-networked flags inspectable. Neither approach guarantees that the space in front of the player is collision-safe.

Build and install only the intended output

From the working directory:

dotnet build Client/Client.csproj -c Debug

Create resources/[local]/doc_cs_first in the server’s active data directory. Copy Client/bin/Debug/net452/Docs.First.Client.net.dll into that resource and create fxmanifest.lua:

fx_version 'cerulean' game 'gta5' client_script 'Docs.First.Client.net.dll'

Run refresh and ensure doc_cs_first in the server console. In the client’s F8 console, run docvehicle adder, then docremove. After rebuilding, replace the deployed DLL and restart the resource; verify the deployed file is the new build rather than assuming an IDE build updates the server folder.

Commands take a command name, a delegate and a restricted flag. On the client, the command’s source argument is not a server authentication decision. Server commands need their own server-side permission and context checks. A chat message also requires the actual stock or compatible chat provider; these examples use console output to avoid that hidden dependency.

Separate server project

For server work, use a separate project with CitizenFX.Core.Server rather than the client package and a different assembly name. The runtime lab supplies the full server project. A minimal server script can register a console-only diagnostic:

// example: first-csharp-server using System; using System.Collections.Generic; using CitizenFX.Core; using static CitizenFX.Core.Native.API; public sealed class FirstServer : BaseScript { public FirstServer() { RegisterCommand("docservercheck", new Action<int, List<object>, string>((source, args, raw) => { if (source != 0) return; Debug.WriteLine("Server-console command received."); }), true); } }

Declare that server build using server_script 'Your.Server.net.dll'. Do not add server source, credentials or server-only debug material to the client download list. Server RPC natives and client entity wrappers have different ownership and availability; see platform migration.

Debug symbols must match the DLL

The project uses embedded portable PDB information. For a diagnostic Debug build, enable DEBUG and TRACE, disable optimization when inspecting source-level stepping, and rebuild. Visual Studio exposes these under Build properties and the advanced debug-information setting.

A separate portable PDB is also supported by the documented workflow: select portable instead of embedded, copy the matching PDB beside the DLL, and include a client PDB in the manifest’s files list when clients need it. A PDB from a different build can produce misleading lines; a missing PDB can leave stack frames without useful locations. Debug artifacts may disclose source paths and should not be published casually. Keep server-only symbols on the server unless there is a deliberate reason to distribute them.

Acceptance and cleanup

Test a valid model, an invalid model, a load deadline, repeated commands during loading, failed creation, removal, resource replacement and resource stop. An unrelated resource stopping must not delete this resource’s vehicle. Compilation checks the actual published classes against the pinned client/server assemblies; it does not simulate GTA streaming, seating, collision or an Enhanced runtime.

Stop doc_cs_first and remove its development startup entry when finished. For communication and asynchronous session handling, continue with C# tasks and exports, events, and current NUI callbacks.