Just a heads up game.connected_players does not give the player_index as the first return
for _, player in pairs (game.connected_players) do
local character = player.character
if character then
local target = player.selected or global.selected[player.index] or nil
if target and target.valid then
global.selected[player.index] = target
Secondly performance could possibly be improved by using on_selected_entity_changed and removing on_tick and player iteration completely