Hello, so in my script I have loops that checks if a player is close enough to 2 different models and if they are then a GUI pops up but if there not then it wont pop up
but
some reason the first for loop is not working, it only works if I remove the second for loop
How do I fix this or Is there another way I could do this? btw ignore the wait(1)
Since those loops are nearly the same thing, you could turn it into a function and use an argument for the location in which GetChildren() is called on. Maybe that will work for you.
Also I just noticed you are setting the same label to visible or not visible depending on if you are near an object, which means you need to choose if it should be visible or not depending if you are near any of the objects, and not just a single one.
I meant that you only need to use 1 for loop, but swap out the parent that the GetChildren() is using in the loop. For example:
local function loopThrough(location)
for _, find in pairs(location:GetChildren()) do
-- the rest of the stuff
end
end
while true do
task.wait(1)
loopThrough(MysteryBoxes)
loopThrough(Doors)
end
Also you should have the function return a boolean if a player was in proximity of an object. Then compare both booleans to determine if the label should be visible.
Rough example:
local found1 = loopThrough(MysteryBoxes)
local found2 = loopThrough(Doors)
if found1 and found2 then
Label.Visible = true
else
Label.Visible = false
end
This is what I meant by returning something from the function to tell the loop if it should show the label or not:
local InteractLabel = script.Parent.InteractLabel
local function InteractGui(Objects)
for _, find in pairs(Objects:GetChildren()) do
local Body = find:WaitForChild("Body")
local CostValue = find:WaitForChild("CostValue")
if Body:IsA("BasePart") and CostValue.ClassName:find("Value") then
if (Body.Position - RootPart.Position).magnitude <= 7 then
return true, Body.Parent.Name.." ["..CostValue.Value.."]"
end
end
end
return false, false
end
while true do
task.wait(1)
local found1, text1 = InteractGui(MysteryBoxes)
local found2, text2 = InteractGui(Doors)
if found1 and found2 then
InteractLabel.Text = text1 or text2 or ""
InteractLabel.Visible = true
else
InteractLabel.Text = ""
InteractLabel.Visible = false
end
end