Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How to delete a car that is named after the localplayer's name?

Asked by
baxzzi 42
6 years ago

So I'm trying to figure out how to spawn a car if the car the player does not have a car. While if the player does have already have a car, delete the existing car and replace the car. Here is the code that I am working with, thanks!

local player = game.Players.LocalPlayer.Name
local car = game.ReplicatedStorage.Cars.PoliceCar
local clonedcar = car:Clone()

function SpawnCar()
    clonedcar.Name = player
    clonedcar.Parent = game.Workspace
end -- everything above here works fine.

script.Parent.MouseButton1Click:connect(function()
    if workspace:FindFirstChild(player) == nil then
        SpawnCar() -- This doesn't work, only works if it is alone. It doesn't work with 'if'
    else
        print("Test") -- This is where I can't seem to figure out how to delete the player's car and spawn in a new one.
    end
end)

1 answer

Log in to vote
0
Answered by 6 years ago
Edited 6 years ago

I might be getting something wrong but...

script.Parent.MouseButton1Click:connect(function()
    if workspace:FindFirstChild(player) == nil then
        SpawnCar()
    else
        print("Test")
    end
end)

The reason your car won't spawn is because you call the function IF the game didn't find anything in workspace with the player's name. If the player's character is still in the game it obviously won't spawn because FindFirstChild found something with that name. The best solution for this problem would be to name the car something different like...

clonedcar.Name = [player .. "car"]

That would get rid of the problem because you would look for an object in workspace with the player's name but with car at the end of the name. So if you search for that name in workspace it won't detect the player because their name wouldn't match with the one you're searching. Another thing you could do is, if there are multiple object with the same name in workspace, you could loop through them and look for their humanoid, or head and stuff like that. Assuming the car doesn't have that it would delete it. Though that's just more complicated.

0
That doesn't work, it comes up with this 11:56:26.478 - Players.DJAppecer.PlayerGui.ScreenGui.TextButton.LocalScript:6: attempt to call upvalue 'player' (a string value) 11:56:26.479 - Stack Begin 11:56:26.480 - Script 'Players.DJAppecer.PlayerGui.ScreenGui.TextButton.LocalScript', Line 6 - global SpawnCar 11:56:26.481 - Script 'Players.DJAppecer.PlayerGui.ScreenGui.TextButton.LocalScript', Line 1 baxzzi 42 — 6y
0
Fixed, I just made the car named after userid. baxzzi 42 — 6y
Ad

Answer this question