Using :Destroy() on a model is destroying the player too

In my game, players are able to spawn in a truck. There is also a Gui button that allows them to delete said truck in case they want to spawn in a different one. I want the button to destroy the truck so they’re able to spawn another one.

However, the button destroys the truck and the player, which is not the desired outcome.

Currently, I have the button triggering this function when it is pressed (this is inside a LocalScript)

local function deleteTruck() -- Deletes the players truck and its cargo.
	
	local deleteVehicle = script.Parent.DeleteVehicle
	local truck = game.Workspace:FindFirstChild(tostring(player.UserId .. "Truck"))
	
	if truck then
		
		if deleteTruckButton.Text == "Are you sure?" then
			
			deleteVehicle:FireServer(truck)
			gui.Notifications.PushMessageLocal:Fire("Truck deleted!")
			deleteTruckButton.Text = "Delete truck"
			
		else -- This should always run first, since the if statement should return false on the first click.
			
			deleteTruckButton.Text = "Are you sure?"
			wait(3)
			deleteTruckButton.Text "Delete truck"
			
		end
	else
		
		deleteTruckButton.Text = "No truck found!"
		wait(1)
		deleteTruckButton.Text = "Delete truck"
		
	end
end

The script fires the server, which does this.

deleteVehicle.OnServerEvent:Connect(function(vehicle)
	vehicle:Destroy()
end)

The truck is indeed destroyed, but so is the player, and I cannot figure out why.

Some extra information, when the truck is spawned in, it’s named after the player’s UserId and then concatenated with “Truck”, so 1111111Truck, which is how I find the specific player’s truck.

Is there something I’m missing that’s killing the player? These are the only two codeblocks relating to the function. My first thought was I was parenting the player to the truck, but this is not the case.

You need to put the Player as first argument in the OnServerEvent. Try:

deleteVehicle.OnServerEvent:Connect(function(Player,vehicle)
	vehicle:Destroy()
end)
3 Likes

You could try what @Valkyrop has given or you could set the Truck’s parent as nil

1 Like

Thank you! I keep forgetting RemoteEvents always pass player through as a parameter.

1 Like

Here is a brief reminder:

FireServer , InvokeServer and FireClient (InvokeClient too, but a bit less safer).

All of them require the Player as their first argument.

FireClient is 'unique`,when used:

--Server
Remote:FireClient(Player,arg1,arg2,..)

--Client
Remote.OnClientEvent:Connect(function(arg1,arg2,...)
1 Like

Thank you, bookmarking this for later for sure.

1 Like