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

How do I stop a script from being cloned too many times?

So basically, I am making a round-based game, and I want a cutscene to play for the players who are ready to join the round before the round begins. Problem is, for that I need to use (or atleast I think so) "for i,v in pairs(game.Players:GetPlayers()) do", which clones the script as many times as how many players are in the server, thus resulting of sometimes playing the cutscene multiple times. Here's the code:

for i,v in pairs(game.Players:GetPlayers()) do
	if v.Backpack.Ready.Value then
		local cutscene = workspace.Map.CutsceneScript:Clone()
		cutscene.Parent = v.Backpack
		cutscene.Disabled = false
	end
end

How do I make the script clone only 1 time?

4 comments

0

debounce

0

could you please try to write a more understandable response? thanks

0

I would have the script destroy itself when it is done running. If that is not the issue, I think the issue would be that the for loop is running inside of an event that fires too often.

0

the problem is, the script is cloned multiple times, so it will play itself anyway because theres multiple ones

2 answers

you can use the break keyword which breaks or stops a loop and continues the script if thats what your looking for. to clone the script one time.

for i,v in pairs(game.Players:GetPlayers()) do
    if v.Backpack.Ready.Value then
        local cutscene = workspace.Map.CutsceneScript:Clone()
        cutscene.Parent = v.Backpack
        cutscene.Disabled = false
	break -- breaks the loop
    end
end

Use :FindFirstChild() == nil You can see more here in wiki: FindFirstChild

Here is a example:

if game.Workspace:FindFirstChild("Hi") == nil then
	print("Not found Hi item")
	local clone = Instance.new("Folder")
	clone.Name = "Hi"
	clone.Parent = game.Workspace
else
	print("Created Hi item")
end

Here is your fixed script:

for i,v in pairs(game.Players:GetPlayers()) do
    if v.Backpack.Ready.Value and v.Backpack:FindFirstChild("CutsceneScript") == nil then
        local cutscene = game.Workspace.Map.CutsceneScript:Clone()
        cutscene.Parent = v.Backpack
        cutscene.Disabled = false
    end
end

If you like to break you can detect if find and break loop

Hope it helped :D

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