Why does my model regenerator break after multiple uses?

I have a button that explodes and regenerates a model it works fine but after multiple uses the model’s Parent is set to nil and the script does not spawn the model into workspace here is my script:

local button = game.Workspace.Explody
local smallship = game.Workspace.smallship
local copy = game.ReplicatedStorage.smallship:Clone()
local debounce = false

button.Touched:Connect(function(hit)
	
	if not debounce then
	
	debounce = true
	
	local ex = Instance.new("Explosion")
	ex.Parent = game.Workspace.smallship
	ex.Position = Vector3.new(-135, 9.5, -35)
	ex.BlastRadius = 50
	ex.DestroyJointRadiusPercent = 0.5
	button.CanCollide = false
	button.Transparency = 1
	wait(16)
	wait(0.1)
	game.Workspace.smallship.Parent = nil
	game.Workspace.smallshipspot.Roof.CanCollide = false
	copy.Parent = game.Workspace
	copy:MoveTo(Vector3.new(-135, 9.5, -35))
	wait(2)
	game.Workspace.smallshipspot.Roof.CanCollide = true
	button.CanCollide = true
	button.Transparency = 0
	wait(3)
	debounce = false
	end
end)

The error I get says this:

smallship is not a valid member of Workspace "Workspace"

I set the parent of the new model to workspace before I set the parent of the previous model so I don’t know whats causing this to happen.

I would move this line:

local copy = game.ReplicatedStorage.smallship:Clone()

Inside the function.

And unless you want to use a broken ship later I would destroy the object instead of setting its parent to nil.

Additionally you should be checking that the small ship exists before you try blowing it up anyways. This is in case something else deletes it like another script or if it falls below the destroy part height. Even if you can’t think of anything that can do it, it wouldn’t particularly hurt to check that it exists first since it will be less likely to break in case something you didn’t expect happens.

Basically flow of your program should be

--[[
Button clicked
debounce passed
If workspace:FindFirstChild(“smallShip”) then
    Create explosion
    Wait
    workspace.smallShip:Destroy()
end

Clone the ship
end function



It is worth noting that you might want a wait if the ship isn’t found so it will still take the same amount of time to respawn if the ship isn’t there too. 

]]
1 Like