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

Why does this script that clones something clones too many models?

Asked by 5 years ago

So i made a spawner. If you click G, it spawn one car in front of your head. But it spawns too much, it spawns 4 of them. whats the problem?

script:

local debounce = false
local uis = game:GetService("UserInputService")
game.ReplicatedStorage.SpawnCarEvent.OnServerEvent:Connect(function(plr)
    uis.InputBegan:connect(function(aey)
        if aey.KeyCode == Enum.KeyCode.G then
            if not debounce then
            wait()
         local car = plr.SelectedCar.Value:Clone()
        car.Parent = game.Players.LocalPlayer.Character
        car.Chassis.Base.Anchored = true
        car.Name = plr.Name..("'s Car")
        car:SetPrimaryPartCFrame(plr.Character.Head.CFrame * CFrame.new(0,0,-10))
        car:MakeJoints()
        car.Chassis.Base.Anchored = false
        debounce = true
        wait()
        debounce = false
            end
            end
        end)
end)
0
Your script is extremely wrong. You have UserInputService and LocalPlayer on the server which obviously won't work. User#19524 175 — 5y
0
but it does work. ieatandisbaconhair 77 — 5y
0
then how do i use userinputservice with onserverevent? ieatandisbaconhair 77 — 5y
0
It worked because you were using Play Solo. User#19524 175 — 5y

1 answer

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

The problem with your script is that you are spawning cars regardless of one already existing. You will need to use the Instance:FindFirstChild() method to check if a car already exists. If it does, just don't spawn a car. You are also using LocalPlayer and UserInputService on the server, which of course will not work. Keep those on the client.

local debounce = false

game.ReplicatedStorage.SpawnCarEvent.OnServerEvent:Connect(function(plr)
    if workspace:FindFirstChild(plr.Name.."'s Car") then return end
    -- line above will check if there is an existing car. if so, end the function

    local car = plr.SelectedCar.Value:Clone()
    car.Chassis.Base.Anchored = true
    car.Name = plr.Name.."'s Car"
    car:SetPrimaryPartCFrame(plr.Character.Head.CFrame*CFrame.new(0,0,-10))
    car.Parent = workspace
    car:MakeJoints()
    debounce = true
    wait(1) -- make it obvious! set 1 to which ever time lol 
    debounce = false
end)

From the client you'll use LocalPlayer, and handle user input and such.

On a side note, PLEASE indent your code as it makes it easier for everyone to read. Although it won't affect how your code runs, it is important to indent code for the sake of readability.

Hope this helped!
Ad

Answer this question