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

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

Asked by
1GlF 42
6 years ago
Edited 6 years ago

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?

0
debounce DeceptiveCaster 3761 — 6y
0
could you please try to write a more understandable response? thanks 1GlF 42 — 6y
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. User#25115 0 — 6y
0
the problem is, the script is cloned multiple times, so it will play itself anyway because theres multiple ones 1GlF 42 — 6y

2 answers

Log in to vote
0
Answered by 6 years ago
Edited 6 years ago

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
Ad
Log in to vote
0
Answered by
yHasteeD 1819 Moderation Voter
6 years ago
Edited 6 years ago

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

Answer this question