For some reason, if I’m not within that distance it only prints (“NOT SHOWING EGG”), which is fine. But if you are within that distance. Both start printing… when It’s only supposed to print (“SHOWING EGG”)?
function HotkeyService:GetNearbyEggs()
local MaxDistance = 10
for _, Egg in pairs(game.Workspace.Eggs:GetChildren()) do
local Char = Player.Character
local Distance = Player:DistanceFromCharacter(Egg.PrimaryPart.Position)
local Billboard = Client:FindFirstChild("EggBillboard")
if Distance < MaxDistance then
print("SHOWING EGG")
else
print("NOT SHOWING EGG")
end
end
end
function HotkeyService:Initialize()
RunService:BindToRenderStep("Eggs", 1, function()
self:GetNearbyEggs()
end)
end
Assuming that you were near an egg when the issue occurred, it appears that the reason it is printing “both” values is because you had some eggs within the maximum distance, while others weren’t. It isn’t actually printing both values, it is just printing one.
function HotkeyService:GetNearbyEggs()
local MaxDistance = 10
local IsNearby = false
for _, Egg in pairs(game.Workspace.Eggs:GetChildren()) do
local Char = Player.Character
local Distance = Player:DistanceFromCharacter(Egg.PrimaryPart.Position)
local Billboard = Client:FindFirstChild("EggBillboard")
if Distance < MaxDistance then
print("SHOWING EGG")
IsNearby = true
break
end
end
if not IsNearby then
print("NOT SHOWING EGG")
end
end
It’s within the function, so every time that function is called it’s a clean slate. If you want it to work otherwise you’d have to make the flag (IsNearby) global.
Here is the solution for those who are interested in how I did it:
Solution:
--// MODULE \\--
-- Variables:
local Client = Player.PlayerGui.Client
local Eggs = game.Workspace.Eggs
local MaxDistance = 10
local NearbyEgg
local ShowingEgg = false
function EggService:GetNearbyEgg()
for _, Egg in pairs(game.Workspace.Eggs:GetChildren()) do
local Distance = Player:DistanceFromCharacter(Egg.PrimaryPart.Position)
if Distance < MaxDistance then
NearbyEgg = tostring(Egg)
end
end
end
function EggService:Initialize()
RunService:BindToRenderStep("Eggs", 1, function()
self:GetNearbyEgg() -- Always gets the NearbyEgg.
if NearbyEgg then -- Checks until NearbyEgg is actually defined.
local Distance = Player:DistanceFromCharacter(Eggs[NearbyEgg].PrimaryPart.Position)
if Distance < MaxDistance then
if not ShowingEgg then
print("Close to " .. NearbyEgg .. "!")
ShowingEgg = true
end
else
print("Not close to any egg.")
ShowingEgg = false
end
end
end)
end
Print:
This printed the name of the closest eggs at the time, if within MaxDistance.