Best Way to Search for Humanoids?

Hey so, I’ve made a hit detection system that uses Raycast, as you can probably assume by the title, When the cast hits a character, I get the exact part I hit (e.g. RightHand, RightLowerLeg, etc)

I know way to get the Humanoid from this while removing duplicate Humanoid’s but mine is kind of lengthy and janky lol.
(just a bunch of array sorting)

I’m wondering if there’s a known “best/efficient way” to filter the Humanoids out of the Raycast!

Thanks in advance for the ideas! :grinning:

What I like to do is setting FilterDescendantInstances of the parameters to {Character}. This is the easiest way to exclude all character’s parts from raycasting as far as I know.

1 Like

AFAIK each raycast can only hit 1 part, so I guess you’re asking how to find unique humanoids for a bunch of raycasts?

You can use a dictionary (hash map) to efficiently find unique values in a table:

function unique(t)
    local found = {}
    local unique = {}
    for _, v in pairs(t) do
        if found[t] then continue end
        found[t] = true
        table.insert(unique, v)
    end
    return unique
end

function findHumanoidsHitByRayCasts(rayCasts: {RaycastResult}): {Humanoid}
    local humanoids = {}
    for _, rayCast in rayCasts do
        local hit = rayCast.Instance
        local humanoid = hit.Parent:FindFirstChild("Humanoid")
        if humanoid then table.insert(humanoids, humanoid)
    end

    return unique(humanoids)
end
1 Like

Wouldn’t this just filter out the everything the Raycast can hit though?

1 Like

Yeah I’m just asking for the best way to get the humanoid from a bunch of random character parts after a bunch of raycasts!

This solution seems good, looks exactly like what I’ve been doing lol, glad to know I’m not just using some arbitrary way, thanks!

1 Like

My bad, misunderstood the topic :stuck_out_tongue: Glad that you found a solution though!

2 Likes

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