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)
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.