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

How do you block duplicates from being created using Instance.new ?

Asked by 6 years ago

I made it so, when you touch a part, a sound plays and loops until another part is touched, but don't worry about the other part, the problem is at the music playing part.

I wrote a successful script that works but it plays in a kind of "round" where it overlaps. Let me try and explain: You hear the first note of the song and then half a second later you hear it again. The song plays about 20 or so times when you walk over the block.

Can anyone make it so that all other duplicates are destroyed or maybe an alternative to help?

Here is the script:

local part = script.Parent
part.Touched:connect(function(hit)
    local h = hit.Parent:FindFirstChild("Humanoid")
    if h then
        wait(1)
        local part2 = Instance.new("Part")
        part2.Name = "MusicPlayerOne"
        part2.Parent = game.Workspace
        part2.Transparency = 1
        part2.CanCollide = false
        part2.Anchored = true
        part2.Position = Vector3.new(-51.3, 15.5, -19.1)
        wait(1)
        local sound = Instance.new("Sound")
        sound.Parent = part2
        sound.Looped = true
        sound.Playing = true
        sound.Volume = 1
        sound.SoundId = "rbxassetid://178276804"
        wait(1)
    end
end)

1 answer

Log in to vote
0
Answered by
H4X0MSYT 536 Moderation Voter
6 years ago
Edited 6 years ago

The touched event often triggers multiple times because of the physics. To counter this, use debounce.. Basically, use an if statement to check whether or not a variable is true. If it is not true, make it true, then run code. This stops it from triggering again. Wait a set amount of time, and set the variable to false again, if you want it to run again.

EDIT: Debounce stops a script from running more than once.

EDIT 2:

local var = false
local part = script.Parent
part.Touched:connect(function(hit)
if var ~= true then
      local h = hit.Parent:FindFirstChild("Humanoid")
      if h then
          wait(1)
          local part2 = Instance.new("Part")
          part2.Name = "MusicPlayerOne"
          part2.Parent = game.Workspace
          part2.Transparency = 1
          part2.CanCollide = false
          part2.Anchored = true
          part2.Position = Vector3.new(-51.3, 15.5, -19.1)
          wait(1)
          local sound = Instance.new("Sound")
          sound.Parent = part2
          sound.Looped = true
          sound.Playing = true
          sound.Volume = 1
          sound.SoundId = "rbxassetid://178276804"
          wait(1)
      end
    end
end)

local var = false

part.Touched:connect(function()
    if var ~= true then
        var = true
        -- code
        -- wait(3) } The two lines for re-usability. you can change the wait to suit your game.
        -- var = false}
    end
end
Ad

Answer this question