I have made an egg hatching system that needs to determine the nearest player to the egg so it can work. However, it only either prints the name of only 1 of the eggs or just prints “Cannot hatch”. Please help, I’m open to any suggestions!
if input.KeyCode == Enum.KeyCode.E then
if canHatch == true and player.Character ~= nil then
local plrPos = player.Character.HumanoidRootPart.Position
for i, v in pairs(Eggs:GetChildren()) do
if nearestEgg == nil then
nearestEgg = v
if (plrPos - v.PrimaryPart.Position).Magnitude < (v.PrimaryPart.Position - plrPos).Magnitude then
nearestEgg = v
Use the debugger to step through the code and see the different variables step by step. You should discover that some variables don’t have the values you expected, indicating where the bug might be. It’s easy to guess though, because the only way “Cannot hatch” can print is if canHatch == true and player.Character ~= nil fails. Since the character probably exists, you must be setting canHatch wrong somewhere else.
local Players = game:GetService("Players")
local Player = Players.LocalPlayer
local Folder = workspace:WaitForChild("Folder")
local function FindChildClosestToPlayer()
local ClosestChild, ClosestDistance = nil, math.huge
for _, Child in ipairs(Folder:GetChildren()) do
local Distance = Player:DistanceFromCharacter(Child.Position)
if Distance < ClosestDistance then
ClosestChild = Child
ClosestDistance = Distance
if ClosestChild then
return ClosestChild, ClosestDistance
local Child, Distance = FindChildClosestToPlayer()
Here’s an example script of how you’d go about finding the closest instance of a folder of instances to a player’s character.
local function findNearestEnemy()
for i,v in pairs(targets:GetChildren()) do
local distance = (script.Parent.hemalurgicSpike.Position - v.Position).magnitude
if previousDistance > distance then
target = v
previousDistance = distance
target.Name = "TARGET"
For some reason, both the target’s names are TARGET