Cannot make a respawning resource thingy

I wanted to make some survival game for practice,but when i tried making the trees respawn i could not make it,this is how far i got:

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local ResourcesAssets = ReplicatedStorage.Assets.Resources

local RespawnTime = 5


local Tree = script.Parent:FindFirstChild("ResourceTree")
Tree.Destroying:Connect(function()
	task.wait(RespawnTime)
	local NewResource = ResourcesAssets.ResourceTree:Clone()
	NewResource.Parent = script.Parent
	NewResource.Position = (script.Parent.Position + Vector3.new(0,5,0))
	Tree = script.Parent:FindFirstChild("ResourceTree")
	

end)


It only respawns 1 time,how can i make it respawn infinitely?
Thanks in advance

1 Like

Wrap your code inside a ‘while loop’.

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local ResourcesAssets = ReplicatedStorage.Assets.Resources

local RespawnTime = 5

local Tree = script.Parent:FindFirstChild("ResourceTree")

while true do
	local NewResource = ResourcesAssets.ResourceTree:Clone()
	NewResource.Parent = script.Parent
	NewResource.Position = (script.Parent.Position + Vector3.new(0,5,0))
	Tree = script.Parent:FindFirstChild("ResourceTree")
	
	task.wait(RespawnTime)
end

Either i wrapped it wrongly or you wanted to make my studio crash

Are you trying to make a new tree every time a tree is destroyed?
If you do it will make sense it will only respawn one time, because you set Tree to a specific tree. I think the following code will work best to fix your problem

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local ResourcesAssets = ReplicatedStorage.Assets.Resources

local RespawnTime = 5

script.Parent.ChildAdded:Connect(function(child)
	if child.Name ~= "ResourceTree" then
		return
	end
    local c
	c = child.Destroying:Connect(function()
		task.wait(RespawnTime)
		local NewResource = ResourcesAssets.ResourceTree:Clone()
		NewResource.Parent = script.Parent
		NewResource.Position = (script.Parent.Position + Vector3.new(0,5,0))
        c:Disconnect()
	end)
end)

Adding to what Downrest said. You can use a while loop, however, instead of it going on forever, create a new variable (0) and add 1 to the variable every time you add a tree (the variable just stands for the current trees) and if the tree is destroyed, then minus 1 from that variable. Looks something around the lines of this:

local trees = 0

while true do
	if (trees < 10) then
         trees += 1
         local NewResource = ResourcesAssets.ResourceTree:Clone()
	     NewResource.Parent = script.Parent
	     NewResource.Position = (script.Parent.Position + Vector3.new(0,5,0))
	     Tree = script.Parent:FindFirstChild("ResourceTree")
    end
	
	task.wait(RespawnTime)
end

Yea that could also work, and will probably be less laggier