So i have multiple Trees with Cut parts. And when my axe its these parts they get destroyed
but for some reason only one tree works and the weirdest part is if i hit a different tree. the working tree acts as if im hitting it?
Basically in short. The Part the Gets Destroyed is a different part than the one that gets Touched
I know its hard to visualise to ive attempted to add a video (but I dont really know how to add a video to a thread without getting it removed so ive attempted it)
If anyone knows what im doing wrong please help me out.
Thanks for reading ~ [redacted]
robloxapp-20210228-2009464.wmv (2.7 MB)
for i = 1, #Trees do
CutPart = Trees[i].CutParts:GetChildren()
for j = 1,#CutPart do
CutPart[j].Touched:connect(function(Hit)
if Hit.Parent.Name == "FireAxe" or Hit.Name == "Axe" then
CutPart[j]:Destroy()
if #Trees[i].CutParts:GetChildren() == 0 then
RunTreeAnimation(Trees[i])
end
end
end)
end
end
A possible issue could be that i and j are used as iteration variables, so by the time .Touched runs they are set to their final value, #Trees and #CutPart, so only the final tree is affected. Try storing them as variables local to the scope instead. Also, using variables to make your code more readable helps to prevent issues like this.
for i = 1, #Trees do
local tree = Trees[i]
CutParts = tree.CutParts:GetChildren()
for j = 1, #CutParts do
local part = CutParts[j]
part.Touched:Connect(function(Hit)
if Hit.Parent.Name == "FireAxe" or Hit.Name == "Axe" then
part:Destroy()
if tree.CutParts:GetChildren() == 0 then
RunTreeAnimation(tree)
end
end
end)
end
end
Basically, .Touched is an event so it runs after the for loop has run, and views i and j as their final value. By saving a reference to the proper item, you are able to act on the proper part.
If that doesn’t work, could you please attach a place file or show your object hierarchy (workspace / object viewer) for more information. Thanks!
1 Like
Thank you this works perfectly now,
I never knew Events ran after the loop 
Glad that works. Events run when invoked, so connections will run at any time from the point they are connected to them being disconnected.
1 Like