Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Why is my For Loop Not Getting Right Objects then Executing code?

=Overview= So i have this script that gets all children of the workspaces than finds the child that is the child to certain items, once it finds the child it will check if it is close enough to the player, than proceed

=Problem= Even though the item i wanted to be selected is in the workspace, it does not continue with the script [ No output errors Btw ]

=Script=

local everyting = game.Workspace:GetChildren()
print('starting') -- is printed
for i, v in ipairs(everyting) do
	wait()
--	print(v.Parent) -- (when running this 'Workspace' was spammed in output ) 
	if v.Parent == 'WoodenWaterFilter' or v.Parent == 'StoneWaterFilter' then	
		print('found suitable filter')--none of thep prints below are printed
		local mag = (Torso.Position - v.Position).magnitude
	
		if mag <= 15 and v.Parent.Storage.Value > 4 then	
			print('Filter is closes enough')
			local Filter = v.Parent
			local Watering = Item
			Item.Thirst.Value = Filter.Thirst.Value + Item.Refill.Amount.Value 
			Filter.Storage.Value = Filter.Storage.Value - Item.Refill.Amount.Value
			wait()
			break
		else
			print('no filter with water close')
		end
	end
end

1 comment

0

I think I know why. On like 6, you check if it is a parent off the WoodenWaterFilter or StoneWaterFilter, but you're looping through the workspace. When looping through the workspace, the workspace will always be the parent.

1 answer

✓ Accepted answer

Since 'everyting' is the children of workspace all of 'v' would be parented to workspace as the loop progresses but then your if statement compares v's parent (which again, should be workspace) to a string. It should be more like:

if v:FindFirstChild("WoodenWaterFilter") or v:FindFirstChild("StoneWaterFilter") then
	--Do stuff.
end

According to your script the loop breaks after finding the first "WoodenWaterFilter" or "StoneWaterFilter" that is within range so it'd be easier on you if you just use :FindFirstChild("WoodenWaterFilter", true) with the second parameter set to true since it would then descend the hierarchy looking for the object.

This discussion is preserved as it was. New answers, comments, and votes are closed.