I want to make a headset script that basically in a loop checks if there are sounds, and if there are then it checks if it has the equalizer and other effects from the headset, and if it doesn’t then it adds them and tags the sound as “Headsetted”, but it lags the game badly. Anyone know how I could make this less laggy? Here’s the code
if vaRep:WaitForChild("Headsets"):FindFirstChild(script.Parent:WaitForChild("Headset").Value) then
local headsetinrep = vaRep:WaitForChild("Headsets"):FindFirstChild(script.Parent:WaitForChild("Headset").Value)
for i,v in pairs(workspace:GetDescendants()) do
if v:IsA("Sound") then
if not colservice:HasTag(v, "Headsetted") then
colservice:AddTag(v, "Headsetted")
for o,p in pairs(headsetinrep.Fire:GetChildren()) do
p:Clone().Parent = v
end
end
end
end
else
for i,v in pairs(workspace:GetDescendants()) do
if v:IsA("Sound") then
if colservice:HasTag(v, "Headsetted") then
if v:FindFirstChild("HeadsetC") then
colservice:RemoveTag(v, "Headsetted")
v.HeadsetC:Destroy()
v.HeadsetE:Destroy()
v.HeadsetR:Destroy()
end
end
end
end
end
Edit: the big issue is that it is inside a task.wait loop inside of a task.spawn function
well the obvious issue in this script is that you are searching unnescessary objects. Another thing that could be causing lag in this script would be that for each sound you find you’re creating a additional loop that may or may not clone multiple instances. I don’t have any other soloution to this issue other than grouping the sounds or naming every sound’s parent to a specific name and using GetChildren() to search for them
I would just go through the workspace once and store all the sounds in a table and then also use Workspace.DescendantAdded as well as Workspace.DescendantRemoving to add new sounds and remove deleted sounds from the table. Then you could just iterate through that table and do your stuff without going through the entire workspace every time.
local Sounds = {}
--Listen for new sounds
workspace.DescendantAdded:Connect(function(Descendant)
if Descendant:IsA("Sound") and not table.find(Sounds, Descendant) then --Is a sound and isn't already in table
table.insert(Sounds, Descendant)
end
end)
--Listen for removing sounds
workspace.DescendantRemoving:Connect(function(Descendant)
if Descendant:IsA("Sound") and table.find(Sounds, Descendant) then --Is a sound and is in table
table.remove(Sounds, table.find(Sounds, Descendant))
end
end)
--Initial check
for _, Descendant in pairs(workspace:GetDescendants()) do
if Descendant:IsA("Sound") and not table.find(Sounds, Descendant) then --Is a sound and isn't already in table
table.insert(Sounds, Descendant)
end
end