Destroy vehicle on resource restart?

I’m creating a resource that heavily depends on vehicles.
One of the main things you do while coding is restarting a script.
Since my script creates a lot of vehicles, they stay on the server whenever I restart the resource - I want them despawned.

How do I run something before the resource is shut-off?

One way I found out is using another resource to track networkID-s and just despawn them, but I don’t like having to code 2 separate resources to do one thing.

Any ideas?

I am running ESX server
‘onClientResourceStop’ doesn’t run if you stop/restart a resource within the resource

AddEventHandler('onResourceStop', function(name)
    if name == GetCurrentResourceName() then -- check if the resource that is restarting, is the resource where our script is located
        --maybe do something? like deleting the vehicles.
    end
end)

Keep in mind that the “onResourceStop” resource needs to run server-side, but that won’t be a problem if you already create the vehicles server-side.

1 Like

You’re completely right! I can destroy the server vehicles using “DeleteEntity”!
Great, thank you so much!

I’ve ran into another issue.
Once there is nobody on the server, server-side vehicles also disappear. Is that expected behavior? How are they then server-side? I’m struggling to understand this.

That shouldn’t happen. Can you share how are you creating the vehicles? Have you tried to run your code on a clean server? (not sure if ESX has any entity cleanup)

I tried debugging the issue. Turns out it was my problem. I restarted the script in-between re-logins.

But that opens another issue, I cannot create a vehicle server-side while nobody is on the server.
Id returned by the server when nobody is on is always 0.

Citizen.CreateThread(function()
    Citizen.Wait(500)
    vehicle = CreateVehicle("t20", -2712.17, 2339.52, 16.77, 0.0, true, true)
    print("Vehicle ID: " .. vehicle)
end)

Also, the netID of the vehicle changes upon the re-log.