Return to Main Page

Getting a player

Page white text.png Description:Getting a player entity with different ways.
link=User:Dim1xs Author:Dim1xs
Calendar.png Created:May 3nd 2024

The Beggining

Fast tutorial that will show you, how to get a player entity, with different ways.

Make sure you have lastest HL2GMED version.

Starting from script

Make sure that you have already read this tutorial.

UTIL.PlayerByIndex(1)
               
This function will return a player from his index.
1 - Game Host

Accordingly, each index is responsible for a specific player.

The maximum index is equal to the maximum number of players on the server.
The index is assigned to the player when he connects to the server and it is IMPOSSIBLE to change it during the game.

You can get a list of players and their index's by executing status command in console.

Output:

hostname: Half-Life 2 GMED
version : 5377866/25 5377866 insecure (unknown)
udp/ip  : nil
map     : sb_testv7 at: 1757 x, -29 y, 88 z
tags    : 
players : 3 humans, 0 bots (16 max)
edicts  : 115 used of 2048 max
# userid name                uniqueid            connected ping loss state  adr
#      2 "Dim1xs"            STEAM_ID_LAN        15:49       41    0 active loopback
#      3 "Player"            STEAM_ID_LAN        07:01       47    0 active 192.168.13.1:27006
#      4 "Player-2"          STEAM_ID_LAN        05:45       49    0 active 192.168.13.1:27007                  
               
userid - is a player index.

This function is shared, it means you can do it from SERVER and CLIENT.

But if you need to get a Local Player, then use this way:
_R.CBasePlayer:GetLocalPlayer()
This function, works ONLY from CLIENT.

Looping

If you need a get a table with all server players, you can make a loop, which will add valid players from index to table.
local tPly = {}
for i=1,16 do
   local ply = UTIL.PlayerByIndex(i)
   if ToBaseEntity(ply) ~= NULL then
      if tPly[i] == ply then 
         tPly[i] = nil
      else
         table.insert(tPly, ply)
      end
   end
end           
If you want to use it in function, add return tPly on function end, so you will be able to use this function to get all players.

Thank you for reading this article, see ya later!

JOIN HL2GMED DISCORD SERVER!