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?
wait(5)
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")
Button.MouseButton1Click:Connect(function()
CanSearch = not CanSearch
print(CanSearch)
if CanSearch == true then
for i, v in pairs(Folder:GetChildren()) do
print(v.Name)
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
end
end
end
return Target
end
print(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
end
elseif CanSearch == false then
NewBeam.Enabled = false
Sound:Play()
Button.Text = "?"
end
end)
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.
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