Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How do I fix my automatic despawn script?

Whenever I sit on the VehicleSeat, it still despawn's.

local car = script.Parent
    local seat = script.Parent.VehicleSeat

    seat.Changed:connect(function()
        if not seat.Occupant then
            wait(20)
            car:Destroy()
        end
    end)

2 comments

0

I think you should have the wait(20) before your if

0

No nvm.. you need some loop to check all the time if someone suddenly sits down, you don't delete it

1 answer

✓ Accepted answer

Well, I recommend not to use Changed as it will trigger if any property of seat changes. The reason why it is still destroying, maybe when you spawn it, the property of seat might change, which trigger the Destroy command. To fix this, just replace Changed with GetPropertyChangedSignal(). It should look like this :

local car = script.Parent
local seat = script.Parent.VehicleSeat

seat:GetPropertyChangedSignal("Occupant"):Connect(function()
	if not seat.Occupant then
		wait(20) 
		if not seat.Occupant then -- Double-check whether the player is sitting or not
			car:Destroy()
		end
	end
end)

-- Now, you were asking why it isn't despawning when you spawn it. It is because the occupant property doesn't change. Here's an example that you can use.
local onSpawn = tick() -- tick() is the number of seconds that have passed from January 1970

wait(20) -- Waits for 20 seconds

if tick() - onSpawn >= 20 and not seat.Occupant then -- If the number of seconds passed is greater than 20 
	if not seat.Occupant then -- If no one sits on it
		car:Destroy() -- Destroys it
	end
end

-- Important : There's no mandatory usage of tick() here. I just added it for educational purposes and double checking the time.

It will trigger whenever the property mentioned in () changes.

Lemme know if it helps!

11 comments

0

It gave me an error saying "Expected ':' not '.' calling member function GetPropertyChangedSignal"

0

Ah sorry my bad

0

make it seat:GetPropertyChnagedSignal

0

Edited the script too

0

seat:GetPropertyChangedSignal only?

0

I edited my code, check that. If you want any explanation, lemme know.

0

The car doesn't despawn when I spawn it, it only works when I get off the car

0

It is because when the car spawns, the property of the occupant doesn't change. Let me edit the code, for it to work.

0

Well, it only works when I get off the car.

0

when you get off the car and then get back in, it despawns.

0

Ya, for that I have edited the code again.

This discussion is preserved as it was. New answers, comments, and votes are closed.