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

How do I make it so that a script can only find one thing at a time?

I'm making a game where you can dash to kill an enemy, but you can kill only one enemy at a time (the most nearby enemy). I know how to script and I'm not asking for any, I just want to get a general idea on how to do something like this.

Thank you for reading!

1 answer

✓ Accepted answer

I would personally use a for loop and magnitude. I know you didn't ask for a script however I'm bad at explaining in words and you would probably understand a script better.

local function getDistance(part1, part2)
	return (part1.Position - part2.Position).magnitude
end

local function findNearestPlayer()
	local nearestPlayer = nil
	for i, plr in pairs(game.Players:GetPlayers()) do
		char = workspace:FindFirstChild(plr.Name)
		if char then
			if i == 1 then
				nearestPlayer = char
			elseif i ~= 1 and getDistance(script.Parent, char.HumanoidRootPart) < getDistance(script.Parent, nearestPlayer.HumanoidRootPart) then
				nearestPlayer = char
			end
		end
	end
	return nearestPlayer
end

I don't currently have access to studio so I don't know how well this works, however I think you can get an idea based off of that. This script (assuming there are no errors) would only work if the script was the child of the part you want the distance to be based off of .You would have to change all of the "script.Parent"s to reference the actual part you want to get the distance from. Hope I helped!

1 comment

1

It sure did help! Thanks for the reply!

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