I am trying to figure out a more efficient way to make my “tool collect” script. What I am doing right now is if the player touches the certain block, then an ObjectValue changes to that block. If a tool is clicked, that block will decrease in size and the player will gain a certain stat. The TouchEvent is not very efficient, and I’m not sure how else to do it. Here is the TouchEvent script:
for i,v in pairs(workspace:GetDescendants()) do
if v.Name == "SugarBlock" then
local touchBlock = v.TouchBlock
touchBlock.Touched:Connect(function(hit)
if hit.Parent:FindFirstChild("Humanoid") then
local plr = game.Players:GetPlayerFromCharacter(hit.Parent)
plr.SugarBlock.Value = v.PrimaryPart
end
end)
touchBlock.TouchEnded:Connect(function(hit)
if hit.Parent:FindFirstChild("Humanoid") then
local plr = game.Players:GetPlayerFromCharacter(hit.Parent)
plr.SugarBlock.Value = nil
end
end)
end
end
That looks fine to me. Touched events are not going to cause performance problems, unless your connected functions are doing really intensive stuff (which yours is not).
Alternatively, you could instead use part:GetTouchingParts() on the player’s character when the player clicks with the tool. Then you use the parts collected from there to see if he/she is touching one of the sugar blocks. Example:
tool.Clicked:Connect(function() -- idk, however you detect clicks
local sugarBlock = nil
for _,v in pairs(character:GetChildren()) do
if (v:IsA("BasePart")) then
local parts = v:GetTouchingParts()
for _,p in pairs(parts) do
if (p.Name == "SugarBlock") then
sugarBlock = p
break
end
end
end
end
if (sugarBlock) then
-- TODO: Do something with the sugar block
end
end)
Performance note: You will notice that there is a nested loop within the first loop. In other words, there’s a loop to get all the character parts, and then another loop to scan through each touched part. A lot of people might complain about that. However, I would argue that this won’t have performance issues because there are only a few character parts in total and there probably won’t be many (if any) touched parts to scan through.