Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Unable to clone and destroy objects consistently. help?

I have explained it inside my script. Here it is:

local Number = math.random(2) --Lets say our friend math.random spawns in "One"


local Storage = game.ServerStorage
local One = Storage["One"]
local Two = Storage["Two"]

while true do --Repeats itself for infinite alternating spawning
	if Number == 1 then One:Clone().Parent = game.Workspace --Puts "One" into workspace
		elseif Number == 2 then Two:Clone().Parent =game.Workspace
	end
	
	wait(3) --waiting until "One" can be deleted.
	
	if game.Workspace:WaitForChild("One") then game.Workspace.One:Destroy() --Destroys "One"
	end
	if game.Workspace:WaitForChild("Two") then game.Workspace.Two:Destroy() --but this one has a "possible infinite yield"
	end
	wait(2)
end

--How do I make sure the script ignores the object that is not located in the workspace?
--I'm also planning on using a variant of this script in a game that has more than two objects, so the solution should work on an infinite amount of objects and be easily duplicated.

--I also may have overlooked something extremely simple...

3 comments

0

Do you mean that sometimes "Two" isn't a member of workspace, and never will be, leading to an infinite sleep? Couldn't you just use "FindFirstChild" instead?

0

If I were to use FindFirstChild, the output would halt the script because it can't find "Two". So that's why I landed on WaitForChild.

0

Update: FindFirstChild did work, I just made a typo when tried it before...

1 answer

✓ Accepted answer

Set one and two to varialbes after line 13 so you can use FindFirstChild

local oneWorkSpace = game.Workspace:FindFirstChild("One")
local twoWorkSpace  = game.Workspace:FindFirstChild("Two")

if oneWorkSpace ~= nil then
	oneWorkSpace:Destroy()
end

if twoWorkSpace  ~= nil then
	twoWorkSpace:Destroy()
end

This discussion is preserved as it was. New answers, comments, and votes are closed.