User talk:Braindawg
Jump to navigation
Jump to search
This page contains examples of VScript performance tips and tricks for Team Fortress 2.
All of these results come from This benchmarking tool You must launch the game in -insecure before using this!
Folding functions
Iterating through players
The most common method of iterating over all players in a map is like so:
::MaxPlayers <- MaxClients().tointeger();
for (local i = 1; i <= MaxPlayers ; i++)
{
local player = PlayerInstanceFromIndex(i)
if (player == null) continue
printl(player)
}
While this solution is simple and efficient enough for most use cases, the fastest way to iterate over all players is to collect them in a separate array when the player has fully loaded into the server, then iterate over this array when needed.
::playerarray <- []
ClearGameEventCallbacks()
//player is activated and loaded into the server
function OnGameEvent_player_activate(params)
{
local player = GetPlayerFromUserID(params.userid)
//check if we're already in the array
if (playerarray.find(player) != null) return
//add player to the array if they don't already exist
playerarray.append(player)
}
//player has left the server
function OnGameEvent_player_disconnect(params)
{
local player = GetPlayerFromUserID(params.userid)
//cache player length value
local playerarray_len = playerarray.len()
//reverse through the player array and remove invalid players
for (local i = playerarray_len - 1; i >= 0; i--)
if (playerarray[i] == null || playerarray[i] == player)
playerarray.remove(i)
}
__CollectGameEventCallbacks(this)
//iterate over array
foreach (player in playerarray)
printl(player)