Help in fixing a merge system that duplicates exponentially

I’m working on a game which is inspired by Merge! by TheBirbsWord

Im a beginner scripter and the problem i’m having is that my merge system glitches out and exponentially duplicates when its suppose to merge into the next level ball

here is the script im using

-- Variables

local cs = game:GetService("CollectionService")
local ballFolder = game.ReplicatedStorage.balls

-- Functions

for _, ball in pairs(cs:GetTagged("ball")) do
        
    local function partSetup(ball)
        ball.Touched:Connect(function(hit)
            if hit:GetAttribute("level") == ball:GetAttribute("level") then
                
                local merge = ball:GetAttribute("level") + 1
                local new = ballFolder:GetChildren()[merge]:Clone()
                local pos = ball.Position
                
                ball:Destroy()
                hit:Destroy()
                
                new.Position = pos
                new.Parent = workspace.balls
            end
        end)
    end
    
    workspace.balls.ChildAdded:Connect(function(child)
        partSetup(child)
    end)
    
end

I think the problem is that the function fires on both balls causing it to duplicate and create more but im not sure how to fix this

i tried repurposing Chrythm’s Merge Kit but it seemed too complicated and defeated the purpose of me learning how to script

try this

-- Variables

local CollectionService = game:GetService("CollectionService")
local ballFolder = game.ReplicatedStorage.balls

-- Functions
local function partSetup(ball)
	ball.Touched:Connect(function(hit)
		if hit:GetAttribute("level") == ball:GetAttribute("level") then
			local merge = ball:GetAttribute("level") + 1
			local new = ballFolder:GetChildren()[merge]:Clone()
			local pos = ball.Position
			
			ball:Destroy()
			hit:Destroy()
			
			new.Position = pos
			new.Parent = workspace.balls
		end
	end)
end

for _, ball in CollectionService:GetTagged("ball") do
    partSetup(ball)
end

workspace.balls.ChildAdded:Connect(function(child)
	partSetup(child)
end)
1 Like