Better way to do this?

This is a simple distance check for server for characters and parts, it works but is there any additional information I need to add like typechecking?

function GetClass(Child):string?
	return Child.ClassName
end
function Distance(Character:Model?, Distance: number?, InitialPart:BasePart?): boolean?
	if GetClass(Character) ~= "Model" then warn("Not a Character model!") return nil end
	if type(Distance) ~= "number" then warn(Distance.. " is not a number!") return nil end
	if typeof(InitialPart) ~= "Instance" then warn(InitialPart.. " is not an instance.. somehow..?") return nil end
	assert(Character.HumanoidRootPart, "HRP doesn't exist yet.")
	assert(InitialPart.Position, tostring(InitialPart).. " doesn't have position.")
	if (Character.HumanoidRootPart.Position - InitialPart.Position).Magnitude <= Distance then return true end
end 
1 Like

I think you are not handling type checking properly.

function Distance(Character:Model?, Distance: number?, InitialPart:BasePart?): boolean?

Given the purpose of the Distance function, there is no case where the Character, Distance and InitialPart parameters are nil, so the ? is not necessary.

if GetClass(Character) ~= "Model" then warn("Not a Character model!") return nil end
if type(Distance) ~= "number" then warn(Distance.. " is not a number!") return nil end
if typeof(InitialPart) ~= "Instance" then warn(InitialPart.. " is not an instance.. somehow..?") return nil end

Type checking is done at compile time, so there is no point in doing the same check at run time.

assert(Character.HumanoidRootPart, "HRP doesn't exist yet.")

This is only useful in the development version. In the release version the function would need to be wrapped in a pcall. This is up to you.

assert(InitialPart.Position, tostring(InitialPart).. " doesn't have position.")

this assert will never fail because a BasePart always has a Position property.

So the code would look something like this

function Distance(Character:Model, Distance: number, InitialPart:BasePart): boolean?
    if Character:FindFirstChild("HumanoidRootPart") then
        return (Character.HumanoidRootPart.Position - InitialPart.Position).Magnitude <= Distance
    end
end

I hope this was helpful.

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.