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

is there a way for this function to activate when a player is near a part?

Hi I'm a basic scripter and I've tried writing this so that it would add a Gui to a player if they're near the part but I don't know how to make it activate. Thanks

Gui = script.menugui

for i, v in pairs(game.Players:GetChildren()) do
	if v.Character ~= nil then
		if v.Character:FindFirstChild("HumanoidRootPart") ~= nil and (script.Parent.Position - v.Character.HumanoidRootPart.Position).magnitude <= 10 and v.PlayerGui:FindFirstChild(Gui) == nil then
		Gui:Clone().Parent = v.PlayerGui
		elseif v.Character:FindFirstChild("HumanoidRootPart") ~= nil and (script.Parent.Position - v.Character.HumanoidRootPart.Position).magnitude > 10 then
		if v.PlayerGui:FindFirstChild(Gui) then 
				v.PlayerGui[Gui]:Destroy() 
			end
		end
	end
end

1 comment

0

dsa

1 answer

✓ Accepted answer

Hello! You are on the right track with the use of magnitude!

If you want to activate a gui. i would recommend using a local script from within the gui itself.

First, we make a table for the parts that can trigger the gui

local NameList={
	'PartA'
}

Then we make a function that finds the closest part from the table.

local preferredDistance = 10 -- Distance from part where it will activate.
local active = false

function returnClosestPart(playerPosition, distancepreferrred)
		local currentdistance = distancepreferrred
	local Chosen = nil
	for i, v in pairs(Loot:GetChildren()) do -- change Loot to where the part's parent.
		if v:IsA('BasePart') then			
			local distance = (playerPosition - v.Position).magnitude			
			if math.floor(distance) <= currentdistance then				
				currentdistance = math.floor(distance)
				Chosen = v				
			end
		end
	end	
	return Chosen	-- Returns the nearest part
end

Then we must activate the part we have chosen if within the distance

while true do
	wait()
	closestPart = returnClosestPart(torso.Position, preferredDistance)
    if closestPart then
        script.Parent.Visible = true -- change to the gui you  want to be visible
	else script.Parent.Visible = false -- same with this one!
    end
end
  • Hope this helps

-Pluginfactory

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