Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How can I stop my script from running early?

I have a script that calculates magnitude(distance between objects) and it makes my GUI visible when I spawn in. It needs to be visible but not when I spawn, its supposed to appear when I am 10 or less studs away. How can I make it appear only when I am 10 or less studs away? Any and all help is appreciated.

Distance = 0

GetFirstDistance = false
GetSecondDistance = false
GetThirdDistance = false

Player = game:GetService("Players").LocalPlayer

function GetDistance(ObjOne, ObjTwo)
	for i = 1,1 do
		Distance = math.ceil((ObjOne.Position - ObjTwo.Position).Magnitude)
		script.Parent.Distance.Text = Distance
	end
end

while true do
	if Distance <= 10 and GetFirstDistance == false then
		script.Parent.Interact.Visible = true
	end
	GetDistance(Player.Character.Torso, workspace.PrologueObjPoints.ObjOne)	
	wait(0.25)
end

2 answers

✓ Accepted answer

First of all, why use a while loop when you can hook onto an existing loop? Secondly, your script doesn't hide the gui when you're no longer near the objects.

Distance = 0

GetFirstDistance = false
GetSecondDistance = false
GetThirdDistance = false

Player = game:GetService("Players").LocalPlayer

function GetDistance(ObjOne, ObjTwo)
        Distance = math.ceil((ObjOne.Position - ObjTwo.Position).Magnitude)
        script.Parent.Distance.Text = Distance
end

game:GetService("RunService").RenderStepped:connect(function()
    GetDistance(Player.Character.Torso, workspace.PrologueObjPoints.ObjOne) 
    if Distance <= 10 then
        script.Parent.Interact.Visible = true
    else
        script.Parent.Interact.Visible = false
    end
end)

1 comment

0

this wont work as the distance is still less than 10 and the getfirstdistance is false, meaning the gui will show no matter what

Your setting the distance to 0 and get first distance to false. also , I would use getdistance differently.

  1. Delete the distance value at the start because this is what is causing the gui to show up.

  2. Put return Distance at the end of the function, and in the while loop instead of just putting the function do, local distance=GetDistance(args) - what this does is in the function you tell it to return a value aka distance so this makes the function return that variable when it is called.

  3. Put an else statement in the if statement in the while loop. The code in the else statment will run if the arguments u put in the if statement return false. You can use this to your advantage by making the gui not visible in the else statement.

This code should work, please comment if it doesnt. I hope this helps!

This discussion is preserved as it was. New answers, comments, and votes are closed.