How to get PlayerApi using raycast or similar to raycast?

I’m working on a udon can select player form far away, but Physics.Raycast can only get gameobject in scene. Any way to get the playerapi when raycast hit on player?

1 Like

Heya,
Because of the very strict limitations on player data in Udon Sharp, as far as I know, there is no way to find players through collision detection outside of the built-in OnPlayerCollision methods. Although, I have found a really clunky solution to the problem by comparing the position of the hit point in the raycast with each player position. Something like this:

Vector3 position = new Vector3(0, 0, 0);
        Vector3 direction = transform.forward;
        float distance = 1;

        VRCPlayerApi targetPlayer;
        VRCPlayerApi[] players = new VRCPlayerApi[20];

        RaycastHit hit;
        if (Physics.Raycast(position, direction, out hit, distance))
        {
            foreach (VRCPlayerApi tPlayer in players) //loop through each player and determine if they meet similar position requirements
            {
                if (tPlayer == null)
                    continue;

                Vector3 playerPos = tPlayer.GetPosition();
                if (Vector3.Distance(new Vector3(hit.point.x, 0, hit.point.z), new Vector3(playerPos.x, 0, playerPos.z)) < 3f) //for the distance formula, id recommend checking it against a value calculated based on player size. I didnt write that portion cause I didnt need it for my use case.
                {
                    targetPlayer = tPlayer;
                    return;
                }
            }
        }

Of course, Id recommend editing the function to reduce a chance of incorrectly detecting a player when they were not hit.