S&box Wiki

Revision Difference

EventSystem#543969

<cat>Code.Misc</cat> <title>Event System</title> The event system is like the Hook system in Garry's Mod. It allows you to register functions on classes to receive a callback on certain global events. ⤶ ⤶ # Registering a callback⤶ ⤶ ## Registering a callback⤶ Adding an `[Event]` attribute will add it to the list to be called. ``` [Event( "server.tick" )] public void MyCallback() { // will get called every server tick } ``` ⤶ # Current Engine Events⤶ ⤶ ## Engine events⤶ The various events called from the engine currently: ⤶ * `client.disconnect` - called from `GameLoop.ClientDisconnected`⤶ * `frame` - called from `GameLoop.PreRender`⤶ * `client.tick` `server.tick` `tick` - tick is always called, client/server are appropriate to their state⤶ * `physics.step` - called from `GameLoop.PostPhysicsStep`⤶ * `client.hotloaded` - called from `HotloadManager.DoSwap`⤶ ⤶ ### client.disconnect⤶ ⤶ Called when a client disconnects.⤶ ```csharp⤶ [Event( "client.disconnected" )]⤶ ```⤶ ⤶ Called from `GameLoop.ClientDisconnected`⤶ ⤶ ### frame⤶ ⤶ Called just before the beginning of a rendering frame.⤶ ⤶ ```csharp⤶ [Event( "frame" )]⤶ ```⤶ ⤶ Called from `GameLoop.PreRender`⤶ ⤶ ### tick⤶ ⤶ Called every <page text="server or client tick">GameLoop#everytick</page> (60 times a second by default).⤶ ⤶ ```csharp⤶ [Event( "tick" )]⤶ [Event( "server.tick" )]⤶ [Event( "client.tick" )]⤶ ```⤶ ⤶ Called from `GameLoop.ServerFrame_Think` and `GameLoop.ClientFrame_Think`.⤶ ⤶ ### physics.step⤶ ⤶ Called after each physics step, this is usually every tick but can be more depending on <page text="Global.PhysicsSubSteps">Sandbox.Global.PhysicsSubSteps</page>.⤶ ⤶ ```csharp⤶ [Event( "physics.step" )]⤶ ```⤶ ⤶ Called from `GameLoop.PostPhysicsStep`.⤶ ⤶ ### hotloaded⤶ ⤶ Called each time your C# is hotloaded after successful recompile.⤶ ⤶ ```csharp⤶ [Event( "hotloaded" )]⤶ ```⤶ ⤶ Called from `HotloadManager.DoSwap`.⤶ ⤶ ## Custom Events⤶ ⤶ You can register your own custom event callbacks and call them.⤶ ⤶ ```csharp⤶ [Event( "mygame.gameover" )]⤶ public void OnGameOver()⤶ {⤶ }⤶ ⤶ public void DoGameOver()⤶ {⤶ Event.Run( "mygame.gameover" )⤶ }⤶ ```⤶ ⤶ # Custom Events⤶ ⤶ You can call your own events. ⤶ ```⤶ Event.Run( "gameover" )```### Event arguments⤶ ⤶ Events can pass any amount of arguments too. ⤶ ```csharp⤶ [Event( "mygame.gameover" )]⤶ public void OnGameOver( Player winner )⤶ {⤶ }⤶ ⤶ public void DoGameOver( Player winner )⤶ {⤶ Event.Run( "mygame.gameover", winner )⤶ }⤶ ```⤶