Hi Friends im starting with the C# code in fivem, following some guides and all i get is running a code on loop, like calling the code every frame, i just want to call my function only if the player is in a vehicle.
class CarLimiter : BaseScript
{
public CarLimiter()
{
EventHandlers["playerConnecting"] += new Action<int,int>(ClientSpawned);
}
private void ClientSpawned(int jugador, int veh)
{
jugador = PlayerPedId();
veh = GetPlayersLastVehicle();
while (IsPedInAnyVehicle(jugador, true))
{
SetVehicleForwardSpeed(veh,15);
Screen.ShowNotification("Your speed is limited");
}
}
playerConnecting is a server side event. The player isn’t connected yet at this stage. This means that the client scripts aren’t running yet either Due to it being server side, you cannot manipulate any entities (like vehicles).
When a player spawns, he’s also not yet in a vehicle. What you want to do instead is, indeed run this every frame, but you’re doing this wrong. You will want to use ticks.
// Make sure this is a client side script
public CarLimiter() {
Tick += OnTick;
}
// This will run every frame!
private async Task OnTick() {
if(Game.PlayerPed.IsInVehicle()) {
Game.PlayerPed.CurrentVehicle.Speed = 15;
Screen.ShowNotification("Your speed is limited");
}
}
I made use of more C# wrappers for this. Game.PlayerPed is the player (so you). We can then check if you are in a vehicle and then change the speed of the vehicle you are currently in.