Custom Game Events

From Valve Developer Community
Jump to: navigation, search

Custom Game Events

CustomGameEventManager is a new system designed to be a more powerful and easier to use version of the game events specified in the 'custom_events.txt' file.

Using this new system, you can send events from server-to-client and client-to-server. You do not have to pre-register your event or the type of data it uses. Lua tables on the server will automatically be cross-converted to and from JS objects on the client.

Server-To-Client Example

Server Lua

The server can send custom game events to all players, a specific team, or an individual player:

local event_data =
{
    key1 = "value2",
    key2 = "value2",
}
CustomGameEventManager:Send_ServerToAllClients( "my_event_name", event_data )
CustomGameEventManager:Send_ServerToTeam( team_number, "my_event_name", event_data )
CustomGameEventManager:Send_ServerToPlayer( player_entity, "my_event_name", event_data )

Client Javascript

In JS you subscribe to custom game events the same way you subscribe to normal game events:

function OnMyEvent( event_data )
{
	$.Msg( "OnMyEvent: ", event_data );
}

GameEvents.Subscribe( "my_event_name", OnMyEvent);

Client-To-Server Example

Client Javascript

Use SendCustomGameEventToServer on the client to send a message to the server:

GameEvents.SendCustomGameEventToServer( "my_event_name", { "key1" : "value1", "key2" : "value2" } );

Server Lua

To listen for a game event on the server, use CustomGameEventManager:RegisterListener. The callback function will be passed the event data, and the entity index of the source of the message (player entity for the client that sent the event.)

function OnMyEvent( eventSourceIndex, args )
	print( "My event: ( " .. eventSourceIndex .. ", " .. args['key2'] .. " )" )
end

CustomGameEventManager:RegisterListener( "my_event_name", OnMyEvent )