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

Can't make and destroy previously made part with a keybind?

Asked by 1 year ago
Edited 1 year ago

Hi I'm trying to make a game and one of the features would be when you press a key it makes a model (cloned) and when you press it again it destroys it but its not actually letting me make the part again and idk why :( pls help

local remote = game.ReplicatedStorage.BedEvent
local currentlyhasflower = false
local model = game.ReplicatedStorage.FlowerBed:Clone()

remote.OnServerEvent:Connect(function(plr, Player)
    if not currentlyhasflower then
        currentlyhasflower = true
        local humanoidRootPart = Player.Character.HumanoidRootPart
        local cFrame = model.PrimaryPart and model.PrimaryPart.CFrame
        local primaryPartCFrame = model:GetPrimaryPartCFrame()
        model:SetPrimaryPartCFrame(humanoidRootPart.CFrame)
        model.Parent = game.Workspace
    else
        model:Destroy()
        currentlyhasflower = false
    end
end)

1 answer

Log in to vote
0
Answered by
Miniller 562 Moderation Voter
1 year ago

That's because you only make one clone of the FlowerBed model, on line 3. When you destroy that, it's gone, so there's no primary part or parent.

It's also weird how you have the plr and the Player parameters. Unless you're expecting Player to be different than the one that fired the event (plr), it's unnecessary.

I made your code a bit shorter but if I deleted some variable that you wanted to use then you can just add them back. It's not always a good idea to have everything in one line, it's ok to make a variable for the humanoidrootpart, however, I don't recommend doing that if you're only using the value once.

local flowerbed

game.ReplicatedStorage.BedEvent.OnServerEvent:Connect(function(plr)
    if not flowerbed then
        flowerbed = game.ReplicatedStorage.FlowerBed:Clone()
        flowerbed:SetPrimaryPartCFrame(plr.Character.HumanoidRootPart.CFrame)
        flowerbed.Parent = workspace
    else
        flowerbed:Destroy()
        flowerbed = nil
    end
end)
Ad

Answer this question