Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
RAGE MP Useful snippets
public static class AsyncHelper
{
public static Task<T> RunAsync<T>(Func<T> callback)
{
var taskCompletion = new TaskCompletionSource<T>();
NAPI.Task.Run(() =>
{
try
{
taskCompletion.TrySetResult(callback());
}
catch (OperationCanceledException)
{
taskCompletion.TrySetCanceled();
}
catch (Exception ex)
{
taskCompletion.TrySetException(ex);
}
});
return taskCompletion.Task;
}
public static Task<T> RunAsync<T>(this GTANetworkMethods.Task gtanTask, Func<T> callback) =>
RunAsync(callback);
}
public class TrailerChangeHelper
{
public delegate void OnVehicleTrailerChangeHandler(Vehicle vehicle, Vehicle trailer);
private readonly OnVehicleTrailerChangeHandler _attachedHandler;
private readonly OnVehicleTrailerChangeHandler _detachedHandler;
private readonly Dictionary<Vehicle, Vehicle> _vehiclesLastTrailers = new Dictionary<Vehicle, Vehicle>();
public TrailerChangeHelper(OnVehicleTrailerChangeHandler attachedHandler, OnVehicleTrailerChangeHandler detachedHandler)
{
_attachedHandler = attachedHandler;
_detachedHandler = detachedHandler;
}
public void HandleVehicleTrailerChange(Vehicle vehicle, Vehicle trailer)
{
if (trailer == null)
return;
if (trailer.Exists)
HandleTrailerAttached(vehicle, trailer);
else
HandleTrailerDetached(vehicle);
}
private void HandleTrailerAttached(Vehicle vehicle, Vehicle trailer)
{
_vehiclesLastTrailers[vehicle] = trailer;
_attachedHandler.Invoke(vehicle, trailer);
}
private void HandleTrailerDetached(Vehicle vehicle)
{
if (!_vehiclesLastTrailers.ContainsKey(vehicle))
{
return;
}
var trailer = _vehiclesLastTrailers[vehicle];
_vehiclesLastTrailers.Remove(vehicle);
_detachedHandler.Invoke(vehicle, trailer);
}
}
public static class VehicleExtensions
{
public static Client GetDriver(this Vehicle vehicle) =>
NAPI.Pools.GetAllPlayers().FirstOrDefault(p => p.Vehicle == vehicle);
public static VehicleHash? GetModelHash(this Vehicle vehicle)
{
if (vehicle?.Model == null)
return null;
if (!Enum.TryParse<VehicleHash>(vehicle.Model.ToString(), out var parsedHash))
return null;
return parsedHash;
}
public static bool TrailerIsBeingTrailered(this Vehicle vehicle)
{
var vehicleTraileringThisTrailer = NAPI.Pools.GetAllVehicles().FirstOrDefault(vehicleInServer => vehicleInServer.Trailer == vehicle &&
vehicleInServer.Trailer != vehicleInServer);
return vehicleTraileringThisTrailer != null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.