Problem with tycoon “Find nearest button” Feature

Recently I have been trying to make a “Find Nearest Button” Tycoon Feature for my game, and I currently have a script to find the closest buyable object. Problem is, it is not working.

You can read my original post for more information:

Here is the script, can anyone tell me what is wrong?


local Player = game.Players.LocalPlayer
local Character = Player.Character or Player.CharacterAdded:Wait()
local Humanoid = Character:FindFirstChild("HumanoidRootPart")

local Button = Player.PlayerGui.FindGui.FindButton
local Sound = script.Sound

local CanSearch = false
local Range = 1000
local Target = nil

local Folder = game.Workspace.TycoonModel.Buttons

local Beam = script.Beam:Clone()
Beam.Parent = Humanoid

local NewBeam = Humanoid:FindFirstChild("Beam")

	CanSearch = not CanSearch
	if CanSearch == true then
		for i, v in pairs(Folder:GetChildren()) do
			if v.Price.Value <= Player.leaderstats.Cash.Value then
				if v.ButtonPart.Transparency == 0 then
					if Player:DistanceFromCharacter(v.ButtonPart.Position) <= Range then
						Range = Player:DistanceFromCharacter(v.ButtonPart.Position)
						Target = v.Name
			return Target
		if Target then
			Button.Text = "X"
			local Attachment0 = Humanoid:FindFirstChild("RootRigAttachment")
			local Attachment1 = Target.ButtonPart.Attachment
			NewBeam.Attachment0 = Attachment0
			NewBeam.Attachment1 = Attachment1
			NewBeam.Enabled = true
	elseif CanSearch == false then
		NewBeam.Enabled = false
		Button.Text = "?"

Thank you to anyone who helps :slight_smile:

Distance from character? never heard of such a function.

Change player:DistanceFromCharacter(v.ButtonPart.Position) to Player:DistanceFromCharacter(v.ButtonPart.Position).Magnitude

Player:DistanceFromCharacter returns the distance between the player’s head and the specified part, in this case, the position of the object I am looping through. I don’t think .Magnitude will fix it.

Something is breaking the for loop though, something inside of the for loop is yielding the script.

I am not quite sure but i think that there are no attachments inside target button that might be it or it detects other parts as buttons instead

Please check out my original post:

It won’t print the target however, so I am thinking it ran into an error somewhere along the way. When cansearch = false, it works, but when the value is true, it doesn’t :thinking:

it finds multiple targets try debouncing code so when it finds first one then it stops searching

Also target variable is set to string local Attachment1 = Target.ButtonPart.Attachment you must do something in here

Can you send a video though i am confused as you are