Weird problem with my while loop

Hey guys, I was writing a slot system for my game, and I decided on using Magnitude to detect when a part is in a slot.

In my code, I have the script iterate through a folder with all the parts, and then detect when a part is nearby.

while true do
	for i,v in ipairs(workspace.samples:GetChildren()) do
		if (v.Position - slot1.Position).Magnitude <= 2 then
			workspace.Data.roundmonsters[team]["1"].Value = v.Monster.Value
			workspace.Data.roundmonsters[team]["1"].Rarity.Value = v.Rarity.Value
			workspace.Data.roundmonsters[team]["1"].Strength.Value = v.Strength.Value
			print("Monster selected: "..v.Monster.Value)
			selected1 = true
		elseif (v.Position - slot1.Position).Magnitude > 2 then
			print("not in range")
			workspace.Data.roundmonsters[team]["1"].Value = "none"
			workspace.Data.roundmonsters[team]["1"].Rarity.Value = ""
			workspace.Data.roundmonsters[team]["1"].Strength.Value = ""
			selected1 = false
		end
	end
	wait(1)
end

However, the output result I get is:

image

Anyone have any idea why this is happening?

Thanks for reading.

A Magnitude of 2 studs is very close, as in right on top. Have you tried setting it to a slightly higher value?

Hmm, I’ll try to set it slightly higher to see if it works.

I did some more testing and it appears that it is waiting for every single part in the folder to be nearby, rather than the closest part. Do you have any idea how to fix this?

You can return / break your loop if the result of your check means you no longer require continued execution of code.

You may want to return / break after line 8.

The problem with this is, if I break it, wouldn’t it stop the code from executing again? I want to be able to make it so that players can move the object away from it again and back.

Right I see, I wasn’t sure exactly what your intentions were. Let me quickly take another look and provide some advice. :slight_smile:

local samples = workspace.samples:GetChildren()
local Closest -- This will be set as the closest spawn to the player
local PlayerPosition = Character.PrimaryPart.Position

while wait(0.0000000001) do
    for i,v in pairs(samples:GetChildren()) do
	    if Closest == nil then
		    Closest = v
	    else
		    if (PlayerPosition - v.Position).magnitude < (Closest.Position - PlayerPosition).magnitude then
			    Closest = v
		    end
	    end
    end
end

Use this to find the closest sample

After finding the closest you will want to see if the closest one is in range:

if (PlayerPosition - Closest.Position).magnitude <= 10 then
    workspace.Data.roundmonsters[team]["1"].Value = v.Monster.Value
    workspace.Data.roundmonsters[team]["1"].Rarity.Value = v.Rarity.Value
    workspace.Data.roundmonsters[team]["1"].Strength.Value = v.Strength.Value
    print("Monster selected: "..v.Monster.Value)
end
1 Like

Thanks for your help! this code worked!

1 Like

No problem! Glad it worked! Good luck with your game! (I’ll fix the indenting now)

1 Like