How to check if object exist effectively during a while loop

  1. What do you want to achieve?

I want to check whether the following cloned object still exists before rendering the follow-up code.

  1. What is the issue? Include screenshots / videos if possible!

I do not know the following steps to achieve the following objective.

  1. What solutions have you tried so far?

I have attempted to try to use FindFirstChild to check whether that object exists, but I believe this would not work since the name of the object is the same.

-- This code will leave a ping showing the distance from the player to the pinged position
local pingClone = ReplicationStorage.ping:Clone()
pingClone.Parent = workspace.trash
pingClone.Position = mousePosition

spawn(function()
		wait(2)
		pingClone:Destroy()
end)
		
while pingClone do -- should checks if cloned object exist, the current condition is not correct
		local magnitude = math.floor((localPlayer.Character:WaitForChild("HumanoidRootPart").Position - pingClone.Position).Magnitude)
		pingClone.BillboardGui.distance.Text = magnitude .. " stud" -- Gives BillboardGui not a valid member after clone part is destroyed.
		wait()
end
2 Likes

first, is your script working? and you just want a more effective way of doing it?

2 Likes

Yes, it is working as intended. I want to clear up unnecessary errors that are outputted into the output.

1 Like

personally, when I saw this post I was going to tell you to use the method that you used, but I think you’re a-ok.

2 Likes

the method you used is quick and effective.

2 Likes

change to

while pingClone.Parent do

Works because when you destroy it sets the parent to nil
The original doesn’t work because your object still exists, it just can’t be interacted with

5 Likes

because of nil or something, right?

1 Like

Whoa, I didn’t know that was a thing! Thank you for your input :+1:

2 Likes

The object no longer exists for all intents and purposes but its variable reference/pointer, in this case “pingClone”, still points to the same address in memory, a userdata value that represents the destroyed instance.

3 Likes