Respawn vehicles on death

From GTA Network Wiki
Jump to: navigation, search

Respawn vehicles on death

Some people were inquiring about respawning vehicles upon their death. Here's a little snippet on how to achieve this.

To begin, we spawn a vehicle using the following method.

VehicleHash myVehicle = API.VehicleNameToModel("Phantom2");
var spawnPos = new Vector3(-382.8018, -107.3787, 38.69825);//Los Santos Customs
var heading = 0f; // Car heading
var myVeh1 = API.CreateVehicle(myVehicle, spawnPos, new Vector3(0, 0, heading), 0, 0, 0);
API.SetEntityData(myVeh1, "RESPAWNABLE", true);
API.SetEntityData(myVeh1, "SPAWN_POS", spawnPos);
API.SetEntityData(myVeh1, "SPAWN_ROT", heading);


Afterwards, add this snippet to your script, hooking it to an onVehicleDeath event.

private void Delay(int ms, Action action)
{
	new Task(() => {
		API.Sleep(ms);
		action();
	}).Start();
}

public void OnVehicleDeath(NetHandle vehicle)
{
	if (API.GetEntityData(vehicle, "RESPAWNABLE") == true)
	{
		Delay(25000, () =>
		{
			var color1 = API.GetVehiclePrimaryColor(vehicle);
			var color2 = API.GetVehicleSecondaryColor(vehicle);
			var model = API.GetEntityModel(vehicle);
	
			var spawnPos = API.GetEntityData(vehicle, "SPAWN_POS");
			var spawnH = API.GetEntityData(vehicle, "SPAWN_ROT");
	
			API.DeleteEntity(vehicle);
	
			var respawnCar = API.CreateVehicle((VehicleHash) model, spawnPos, new Vector3(0, 0, spawnH), color1, color2);
			// You can also add more things, like vehicle modifications, number plate, etc.	
			API.SetEntityData(respawnCar, "RESPAWNABLE", true);
			API.SetEntityData(respawnCar, "SPAWN_POS", spawnPos);
			API.SetEntityData(respawnCar, "SPAWN_ROT", spawnH);
		});	
	}
	else
	{
		Delay(10000, () =>
		{
			API.DeleteEntity(vehicle);
			//Delete Vehicles which should not respawn after 10 seconds
		});
	}
}	

That's all there is to it. You now have vehicles that will respawn upon their death!

Forum: Respawning vehicles