### Example Leaderboard System and Usage (C#)
Source: https://wiki.facepunch.com/steamworks/Leaderboards~edit
A comprehensive C# example class (`SteamLeaderBoardSystem`) for managing Steamworks leaderboards, including methods to get, submit, and replace scores. It also includes a `MonoBehaviour` example (`SteamLeaderBoard`) demonstrating how to initialize and use these leaderboard functions within a Unity project.
```csharp
using System;
using System.Threading.Tasks;
using Steamworks;
using Steamworks.Data;
using UnityEngine;
public static class SteamLeaderBoardSystem
{
///
/// This function will only replace your last score if the new one is better.
///
///
///
///
public static async Task SubmitLeaderboard(Steamworks.Data.Leaderboard leaderboard, int value, int[] details = null)
{
var leaderboardUpdate = await leaderboard.SubmitScoreAsync(value, details ?? Array.Empty());
if (!leaderboardUpdate.HasValue)
{
Debug.LogError("leaderboardUpdate is null");
return;
}
Debug.Log(leaderboardUpdate.Value);
}
///
/// Force your score to be replaced
///
///
///
///
public static async Task ReplaceLeaderboard(Steamworks.Data.Leaderboard leaderboard, int value, int[] details = null)
{
var leaderboardUpdate = await leaderboard.ReplaceScore(value, details ?? Array.Empty());
if (!leaderboardUpdate.HasValue)
{
Debug.LogError("leaderboardUpdate is null");
return;
}
Debug.Log(leaderboardUpdate.Value);
}
public static async Task GetLeaderBoards(string lbName)
{
try
{
return await FindOrCreateLeaderboardAsync(lbName);
}
catch (Exception e)
{
Debug.LogError(e);
}
return null;
}
private static async Task FindOrCreateLeaderboardAsync(string leaderboardName)
{
try
{
return await SteamUserStats.FindOrCreateLeaderboardAsync(leaderboardName, LeaderboardSort.Ascending, LeaderboardDisplay.Numeric);
}
catch (Exception e)
{
Debug.LogError(e);
}
return null;
}
}
public class SteamLeaderBoard : MonoBehaviour
{
private const string LeaderboardName = "MyLeaderboard";
private Steamworks.Data.Leaderboard _lb;
private async void Awake()
{
try
{
var lb = await SteamLeaderBoardSystem.GetLeaderBoards(LeaderboardName);
if (lb.HasValue)
_lb = lb.Value;
else
Debug.LogError("leaderboard did not have value");
}
catch (Exception e)
{
Debug.LogError($"Error loading leaderboards: {e.Message}");
// Optionally, you could handle the exception, e.g., retry logic or fallback behavior
}
}
#region TEST
[ContextMenu("ReplaceScoreTest")]
private void ReplaceScoreTest()
{
var entry = new LeaderboardScore(1234.1829f, 12345789);
ReplaceSpeedScore(entry);
}
#endregion
#region ReplaceScores
private void ReplaceSpeedScore(LeaderboardScore entry)
{
_ = SteamLeaderBoardSystem.ReplaceLeaderboard(_lb, entry.TimeI, entry.Details);
}
#endregion
}
// Struct to hold data for ease-of-use and re-use-ability
public struct LeaderboardScore
{
public readonly int Score;
public readonly int SomeOtherValue;
public readonly int[] Details;
public LeaderboardScore(int score, int someOtherValue)
{
Score = score;
SomeOtherValue = someOtherValue;
Details = new int[] { score, someOtherValue }; // Example details
}
public int TimeI => Score; // Assuming Score is analogous to Time for this example
}
```
--------------------------------
### Basic Steamworks Usage Examples
Source: https://wiki.facepunch.com/steamworks/Setting_Up~diff%3A524489
Demonstrates common functionalities provided by Facepunch.Steamworks, such as retrieving player information, triggering screenshots, setting user statistics, accessing inventory, and listing friends. These examples show how to interact with various Steam interfaces.
```csharp
var playername = SteamClient.Name;
var playersteamid = SteamClient.SteamId;
SteamScreenshots.TriggerScreenshot();
Steamworks.SteamUserStats.SetStat( "deaths", value );
foreach ( var item in Steamworks.SteamInventory.Items )
{
Debug.Log( $"{item.Def.Name} x {item.Quantity}" );
}
foreach ( var player in SteamFriends.GetFriends() )
{
Debug.Log( $"{player.Name}" );
}
```
--------------------------------
### Example Usage of SteamLeaderBoardSystem in C#
Source: https://wiki.facepunch.com/steamworks/Leaderboards~edit
This code provides an example of how to use the `SteamLeaderBoardSystem` class in a Unity MonoBehaviour. It retrieves a leaderboard, handles potential errors, and demonstrates a basic setup for leaderboard interaction within a game.
```csharp
using UnityEngine;
public class SteamLeaderBoard : MonoBehaviour {
private const string LeaderboardName = "MyLeaderboard";
private Steamworks.Data.Leaderboard _lb;
private async void Awake() {
try {
var lb = await SteamLeaderBoardSystem.GetLeaderBoards(LeaderboardName);
if (lb.HasValue)
_lb = lb.Value;
else
Debug.LogError("leaderboard did not have value");
} catch (Exception e) {
Debug.LogError($"Error loading leaderboards: {e.Message}");
// Optionally, you could handle the exception, e.g., retry logic or fallback behavior
}
}
#region TEST
[ContextMenu("ReplaceScoreTest")]
private void ReplaceScoreTest() {
var entry = new LeaderboardScore(1234.1829f, 12345789);
ReplaceSpeedScore(entry);
}
#endregion
#region ReplaceScores
private void ReplaceSpeedScore(LeaderboardScoreentry) {
_ = SteamLeaderBoardSystem.ReplaceLeaderboard(_lb, entry.TimeI, entry.Details);
}
#endregion
}
// Struct to hold data for ease-of-use and re-use-ability
public struct LeaderboardScore {
public readonly int Score;
public readonly int SomeOtherValue;
public readonly int[] Details;
public LeaderboardScore(int score, int someOtherValue)
```
--------------------------------
### Example Leaderboard Management in Unity - C#
Source: https://wiki.facepunch.com/steamworks/Leaderboards~diff%3A563589
A Unity MonoBehaviour script demonstrating how to use the `SteamLeaderBoardSystem` to get a leaderboard and trigger score replacement via context menu. It handles potential errors during leaderboard loading. Dependencies include Steamworks SDK and Unity.
```csharp
using System;
using System.Threading.Tasks;
using Steamworks;
using Steamworks.Data;
using UnityEngine;
public class SteamLeaderBoard : MonoBehaviour
{
private const string LeaderboardName = "MyLeaderboard";
private Steamworks.Data.Leaderboard _lb;
private async void Awake()
{
try
{
var lb = await SteamLeaderBoardSystem.GetLeaderBoards(LeaderboardName);
if (lb.HasValue) _lb = lb.Value;
else Debug.LogError("leaderboard did not have value");
}
catch (Exception e)
{
Debug.LogError($"Error loading leaderboards: {e.Message}");
}
}
[ContextMenu("ReplaceScoreTest")]
private void ReplaceScoreTest()
{
var entry = new LeaderboardEntry(1234.1829f, 12345789);
ReplaceSpeedScore(entry);
}
private void ReplaceSpeedScore(LeaderboardEntry entry)
{
_ = SteamLeaderBoardSystem.ReplaceLeaderboard(_lb, entry.TimeI, entry.Details);
}
}
public struct LeaderboardEntry
{
public readonly int Score;
public readonly int Som
public int TimeI { get; }
public int[] Details { get; }
public LeaderboardEntry(float score, int timeI, params int[] details)
{
Score = (int)score;
TimeI = timeI;
Details = details;
}
}
```
--------------------------------
### SteamServerInit VersionString
Source: https://wiki.facepunch.com/steamworks/~pagelist_p=2&sort=
Gets or sets the version string for the server.
```APIDOC
## GET or POST /websites/wiki_facepunch_steamworks/SteamServerInit.VersionString
### Description
Retrieves or sets the version identifier string for the dedicated server software.
### Method
GET (to retrieve), POST (to set)
### Endpoint
/websites/wiki_facepunch_steamworks/SteamServerInit.VersionString
### Parameters
#### Request Body (for POST)
- **value** (string) - Required - The version string (e.g., "1.2.3").
### Request Example (POST)
```json
{
"value": "1.0.0-beta"
}
```
### Response
#### Success Response (200)
- **versionString** (string) - The current server version string.
#### Response Example
```json
{
"versionString": "1.0.0-beta"
}
```
```
--------------------------------
### SteamServerInit GameDescription
Source: https://wiki.facepunch.com/steamworks/~pagelist_p=2&sort=
Gets or sets the description for the game server.
```APIDOC
## GET or POST /websites/wiki_facepunch_steamworks/SteamServerInit.GameDescription
### Description
Retrieves or sets the descriptive string for the game being hosted by the server.
### Method
GET (to retrieve), POST (to set)
### Endpoint
/websites/wiki_facepunch_steamworks/SteamServerInit.GameDescription
### Parameters
#### Request Body (for POST)
- **value** (string) - Required - The description string for the game.
### Request Example (POST)
```json
{
"value": "A thrilling space exploration game."
}
```
### Response
#### Success Response (200)
- **gameDescription** (string) - The current game description.
#### Response Example
```json
{
"gameDescription": "A thrilling space exploration game."
}
```
```
--------------------------------
### C# Example: Get Steam Friends List using Steamworks.Net
Source: https://wiki.facepunch.com/steamworks/~diff%3A517221
This C# code snippet demonstrates how to retrieve a list of friends from Steam using the Steamworks.Net library. It iterates through the friends, logs their count, and prints their names and online status. Dependencies include the Steamworks.Net library and Unity's Debug class.
```csharp
int friendCount = SteamFriends.GetFriendCount(EFriendFlags.k_EFriendFlagImmediate);
Debug.Log("[STEAM-FRIENDS] Listing " + friendCount + " Friends.");
for (int i = 0; i < friendCount; ++i) {
CSteamID friendSteamId = SteamFriends.GetFriendByIndex(i, EFriendFlags.k_EFriendFlagImmediate);
string friendName = SteamFriends.GetFriendPersonaName(friendSteamId);
EPersonaState friendState = SteamFriends.GetFriendPersonaState(friendSteamId);
Debug.Log(friendName + " is " + friendState);
}
```
--------------------------------
### SteamServerInit IpAddress
Source: https://wiki.facepunch.com/steamworks/~pagelist_p=2&sort=
Gets or sets the IP address for the server.
```APIDOC
## GET or POST /websites/wiki_facepunch_steamworks/SteamServerInit.IpAddress
### Description
Retrieves or sets the IP address that the server will bind to.
### Method
GET (to retrieve), POST (to set)
### Endpoint
/websites/wiki_facepunch_steamworks/SteamServerInit.IpAddress
### Parameters
#### Request Body (for POST)
- **value** (string) - Required - The IP address (e.g., "0.0.0.0" to listen on all interfaces).
### Request Example (POST)
```json
{
"value": "192.168.1.100"
}
```
### Response
#### Success Response (200)
- **ipAddress** (string) - The current IP address the server is bound to.
#### Response Example
```json
{
"ipAddress": "0.0.0.0"
}
```
```
--------------------------------
### SteamServerInit QueryPort
Source: https://wiki.facepunch.com/steamworks/~pagelist_p=2&sort=
Gets or sets the query port for the server.
```APIDOC
## GET or POST /websites/wiki_facepunch_steamworks/SteamServerInit.QueryPort
### Description
Retrieves or sets the network port used for server queries (e.g., by master servers).
### Method
GET (to retrieve), POST (to set)
### Endpoint
/websites/wiki_facepunch_steamworks/SteamServerInit.QueryPort
### Parameters
#### Request Body (for POST)
- **value** (integer) - Required - The port number for server queries.
### Request Example (POST)
```json
{
"value": 27016
}
```
### Response
#### Success Response (200)
- **queryPort** (integer) - The current query port.
#### Response Example
```json
{
"queryPort": 27016
}
```
```
--------------------------------
### Get Friend List in C# using Facepunch.Steamworks
Source: https://wiki.facepunch.com/steamworks/~diff%3A528911
This code provides an example of how to retrieve and display a list of friends using the Facepunch.Steamworks library in C#. It iterates through the friends and outputs their ID, name, online status, and Steam level to the console. Requires Facepunch.Steamworks to be installed and initialized correctly.
```csharp
foreach ( var friend in SteamFriends.GetFriends() )
{
Console.WriteLine( $"{friend.Id}: {friend.Name}" );
Console.WriteLine( $"{friend.IsOnline} / {friend.SteamLevel}" );
}
```
--------------------------------
### Get App Install Directory
Source: https://wiki.facepunch.com/steamworks/~pagelist_p=0&sort=views
Retrieves the installation directory of the game on the user's system. This can be useful for accessing game files or resources. It typically returns a string path.
```C#
Steamworks.SteamApps.AppInstallDir;
```
--------------------------------
### Basic Steamworks Usage Examples
Source: https://wiki.facepunch.com/steamworks/Setting_Up
Demonstrates common Steamworks API usage patterns, including checking if Steam is valid, accessing player name and Steam ID, triggering a screenshot, setting a user stat, iterating through inventory items, and retrieving a list of friends.
```csharp
var playername = SteamClient.Name;
var playersteamid = SteamClient.SteamId;
SteamScreenshots.TriggerScreenshot();
Steamworks.SteamUserStats.SetStat( "deaths", value );
foreach ( var item in Steamworks.SteamInventory.Items ) {
Debug.Log( $"{item.Def.Name} x {item.Quantity}" );
}
foreach ( var player in SteamFriends.GetFriends() ) {
Debug.Log( $"{player.Name}" );
}
```
--------------------------------
### SteamServerInit WithQueryShareGamePort
Source: https://wiki.facepunch.com/steamworks/~pagelist_p=2&sort=
Configures the server to share the game port for queries.
```APIDOC
## POST /websites/wiki_facepunch_steamworks/SteamServerInit.WithQueryShareGamePort
### Description
Configures the dedicated server to use the same port for both game traffic and server queries.
### Method
POST
### Endpoint
/websites/wiki_facepunch_steamworks/SteamServerInit.WithQueryShareGamePort
### Parameters
None
### Request Example
```json
{}
```
### Response
#### Success Response (200)
Indicates the configuration was applied successfully.
#### Response Example
```json
{
"status": "success",
"message": "Query port set to share game port."
}
```
```
--------------------------------
### Initialize Steam Client
Source: https://wiki.facepunch.com/steamworks/Setting_Up~diff%3A524489
Initializes the SteamClient with a given AppID. It's crucial to wrap this call in a try-catch block to handle potential exceptions, such as Steam not being open or DLLs not being found. This is recommended to be called on an object with [DontDestroyOnLoad](https://docs.unity3d.com/ScriptReference/Object.DontDestroyOnLoad.html) in Unity.
```csharp
try
{
Steamworks.SteamClient.Init( 252490, true );
}
catch ( System.Exception e )
{
// Something went wrong! Steam is closed?
}
```
--------------------------------
### SteamServerInit Configuration
Source: https://wiki.facepunch.com/steamworks/~pagelist_p=2&sort=
Provides configuration settings for the dedicated server initialization.
```APIDOC
## GET /websites/wiki_facepunch_steamworks/SteamServerInit
### Description
Retrieves various configuration parameters used during the initialization of the dedicated server.
### Method
GET
### Endpoint
/websites/wiki_facepunch_steamworks/SteamServerInit
### Parameters
None
### Request Example
```json
null
```
### Response
#### Success Response (200)
- **dedicatedServer** (boolean) - Indicates if it's a dedicated server.
- **gameDescription** (string) - A description of the game.
- **gamePort** (integer) - The port for game traffic.
- **ipAddress** (string) - The IP address of the server.
- **modDir** (string) - The directory for mods.
- **queryPort** (integer) - The port for server queries.
- **secure** (boolean) - Indicates if the server is secure.
- **steamPort** (integer) - The port for Steam communication.
- **versionString** (string) - The version string of the server.
#### Response Example
```json
{
"dedicatedServer": true,
"gameDescription": "My Awesome Game",
"gamePort": 27015,
"ipAddress": "0.0.0.0",
"modDir": "mods",
"queryPort": 27016,
"secure": true,
"steamPort": 27017,
"versionString": "1.0.0"
}
```
```
--------------------------------
### Get DLC Information
Source: https://wiki.facepunch.com/steamworks/~pagelist_p=0&sort=views
Retrieves detailed information about the game's DLC. This can include names, descriptions, and installation status. Requires DLC App ID.
```C#
Steamworks.SteamApps.DlcInformation;
```
--------------------------------
### Steamworks.SteamApps.OnNewLaunchParameters
Source: https://wiki.facepunch.com/steamworks/SteamApps
This event is posted after the user gains executes a Steam URL with command line or query parameters while the game is already running. The new parameters can be queried with GetLaunchQueryParam and GetLaunchCommandLine.
```APIDOC
## Steamworks.SteamApps.OnNewLaunchParameters
### Description
This event is posted after the user executes a Steam URL with command line or query parameters, such as `steam://run/appid//-commandline/?param1=value1(and)param2=value2(and)param3=value3`, while the game is already running. The new parameters can be queried with `GetLaunchQueryParam` and `GetLaunchCommandLine`.
### Method
Event (asynchronous)
### Endpoint
N/A (This is an event within the Steamworks SDK)
### Parameters
#### Event Arguments
- **None**: This event does not directly pass arguments. New parameters should be queried using `GetLaunchQueryParam` and `GetLaunchCommandLine`.
### Request Example
N/A (This is an event, not an endpoint to be called directly)
### Response
#### Event Trigger
- **System.Action**: The event itself returns a `System.Action` delegate.
#### Response Example
N/A (This is an event, not an endpoint to be called directly)
```
--------------------------------
### C# Example: Get Steam Friends List using Facepunch.Steamworks
Source: https://wiki.facepunch.com/steamworks/~diff%3A517221
This C# code snippet shows how to fetch a list of Steam friends using the Facepunch.Steamworks wrapper. It provides a more concise way to access friend data, including their ID, name, and online status. This snippet requires the Facepunch.Steamworks library.
```csharp
foreach ( var friend in SteamFriends.GetFriends() )
{
Console.WriteLine( "{friend.Id}: {friend.Name}" );
Console.WriteLine( "{friend.IsOnline} / {friend.SteamLevel}" );
}
```
--------------------------------
### Client Connection Example
Source: https://wiki.facepunch.com/steamworks/Creating_A_Socket_Server~diff%3A562019
This C# code illustrates how a client can connect to a server using either ConnectNormal or ConnectRelay. It shows the creation of a ConnectionManager instance to establish the connection, potentially to a specific host identified by SteamID.
```csharp
ConnectionManager hostConnection = SteamNetworkingSockets.ConnectRelay(hostSteamID);
```
--------------------------------
### SteamServer.Init
Source: https://wiki.facepunch.com/steamworks/~pagelist_p=0&sort=views
Initializes the Steam server.
```APIDOC
## SteamServer.Init
### Description
Initializes the Steam server.
### Method
POST
### Endpoint
/SteamServer/Init
### Parameters
#### Request Body
- **port** (uint16) - Required - The port number for the server.
- **steam_server_query_port** (uint16) - Required - The query port for the server.
- **secure** (boolean) - Required - Whether to use secure connections.
```
--------------------------------
### Access Steamworks Features
Source: https://wiki.facepunch.com/steamworks/Setting_Up~edit
Demonstrates how to access various Steamworks features and functionalities. This includes retrieving player information, triggering screenshots, setting player statistics, iterating through player inventory, and fetching a list of friends. It also shows how to check if the Steam client is valid and accessible.
```csharp
var playername = SteamClient.Name;
var playersteamid = SteamClient.SteamId;
SteamScreenshots.TriggerScreenshot();
Steamworks.SteamUserStats.SetStat( "deaths", value );
foreach ( var item in Steamworks.SteamInventory.Items ) {
Debug.Log( $"{item.Def.Name} x {item.Quantity}" );
}
foreach ( var player in Steamworks.SteamFriends.GetFriends() ) {
Debug.Log( $"{player.Name}" );
}
```
--------------------------------
### Get a Stat Value
Source: https://wiki.facepunch.com/steamworks/Get_a_Stat_Value~edit
Retrieves an integer or float stat value for the current user. Ensure that the stat is configured and published on the Steamworks website.
```APIDOC
## Get a Stat Value
### Description
Stats are stored as either integers or floats. Before using a stat, it must be set up on the Steamworks Site and the changes published.
### Method
Not Applicable (this describes a library function, not an HTTP endpoint)
### Endpoint
Not Applicable
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```csharp
// To get an integer stat
var killCount = Steamworks.SteamUserStats.GetStatInt( "KillCount" );
// To get a float stat
var healthTaken = Steamworks.SteamUserStats.GetStatFloat( "HealthTaken" );
```
### Response
#### Success Response (200)
Not Applicable (this describes a library function, not an HTTP endpoint)
#### Response Example
Not Applicable
```
--------------------------------
### Check if DLC is Installed
Source: https://wiki.facepunch.com/steamworks/~pagelist_p=0&sort=views
Checks if a specific Downloadable Content (DLC) package is installed for the game. Essential for enabling or disabling DLC-specific features. Requires DLC App ID.
```C#
Steamworks.SteamApps.IsDlcInstalled();
```
--------------------------------
### Get Leaderboard in C#
Source: https://wiki.facepunch.com/steamworks/Leaderboards~edit
This code snippet shows how to retrieve a leaderboard using its name in C#. It uses the FindLeaderboardAsync function to get an existing leaderboard. Includes a note about null return values and how to handle them.
```csharp
var leaderboard = await SteamUserStats.FindLeaderboardAsync( "MyLeaderboard" );
```
--------------------------------
### Create and Configure Server List Request in C#
Source: https://wiki.facepunch.com/steamworks/Get_Server_List~diff%3A523917
Demonstrates how to create an Internet server request, add filters, set up a callback for server updates, and initiate the query. It also shows how to handle server responses and cancel the request.
```csharp
Request = new Steamworks.ServerList.Internet();
// Show only secure servers
Request.AddFilter( "secure", "1" );
// AND with the next 1 rule (if not it'll OR)
Request.AddFilter( "and", "1" );
// Show only servers that are the same version
Request.AddFilter( "gametype", GameVersionString );
Request.OnChanges += OnServersUpdated;
Request.RunQueryAsync( 30 );
void OnServersUpdated() {
// No reponsive servers yet, bail
if ( Request.Responsive.Count == 0 )
return;
// Process each responsive server
foreach ( var s in Request.Responsive ) {
ServerResponded( s );
}
// Clear the responsive server list so we don't
// reprocess them on the next call.
Request.Responsive.Clear();
}
void ServerResponded( ServerInfo server ) {
// Do whatever you want with the server information
Log( $"{server.Name} Responded!" );
}
if ( Request != null ) {
Request.Dispose();
Request = null;
}
```
--------------------------------
### Get Integer and Float Stats - C#
Source: https://wiki.facepunch.com/steamworks/Get_a_Stat_Value~diff%3A517228
Retrieves integer and float stat values for a user using Facepunch.Steamworks. Ensure that the stats ('KillCount', 'HealthTaken') have been defined and published on the Steamworks website prior to calling these functions.
```csharp
var killCount = Steamworks.SteamUserStats.GetStatInt( "KillCount" );
var healthTaken = Steamworks.SteamUserStats.GetStatFloat( "HealthTaken" );
```
--------------------------------
### Initialize SteamClient
Source: https://wiki.facepunch.com/steamworks/Setting_Up
Initializes the SteamClient with your application's Steam App ID. This is a critical step to enable Steamworks functionality. It can throw an exception if Steam is not running, DLLs are missing, or permissions are lacking. Ensure you wrap this call in a try-catch block to handle potential errors.
```csharp
try {
Steamworks.SteamClient.Init( 252490, true );
} catch ( System.Exception e ) {
// Something went wrong! Steam is closed?
}
```
--------------------------------
### Initialize Steamworks Client in Unity
Source: https://wiki.facepunch.com/steamworks/Installing_For_Unity~diff%3A517233
Initializes the Steamworks client with a given App ID. It's crucial to wrap this call in a try-catch block to handle potential exceptions during initialization, such as Steam not running or missing DLLs. This should only be called once during application startup.
```csharp
try
{
Steamworks.SteamClient.Init( 252490 );
}
catch ( System.Exception e )
{
// Handle exceptions: Steam closed, missing steam_api.dll, permission issues, etc.
}
```
--------------------------------
### Get Stat Value (Int and Float) - Facepunch.Steamworks
Source: https://wiki.facepunch.com/steamworks/Get_a_Stat_Value~diff%3A517227
Retrieves integer and float-based stats for a user. Ensure that each stat is configured and published on the Steamworks Site prior to usage. This function requires the Steamworks.NET library to be initialized.
```csharp
var killCount = Steamworks.SteamUserStats.GetStatInt( "KillCount" );
var healthTaken = Steamworks.SteamUserStats.GetStatFloat( "HealthTaken" );
```
--------------------------------
### Create and Query Server List Request (C#)
Source: https://wiki.facepunch.com/steamworks/Get_Server_List~edit
This snippet demonstrates how to create an internet server list request, add filters, set up a callback for updates, and run the query asynchronously. It uses the `Steamworks.ServerList.Internet` class and requires the Facepunch.Steamworks library.
```csharp
Request = new Steamworks.ServerList.Internet();
// Show only secure servers
Request.AddFilter( "secure", "1" );
// AND with the next 1 rule (if not it'll OR)
Request.AddFilter( "and", "1" );
// Show only servers that are the same version
Request.AddFilter( "gametype", GameVersionString );
Request.OnChanges += OnServersUpdated;
Request.RunQueryAsync( 30 );
```
--------------------------------
### Create and Run Server List Request (C#)
Source: https://wiki.facepunch.com/steamworks/Get_Server_List~diff%3A526431
Demonstrates creating an Internet server list request, adding filters, setting up a callback for server updates, and running the query asynchronously. The callback processes responsive servers and clears them for reprocessing.
```csharp
Request = new Steamworks.ServerList.Internet();
// Show only secure servers
Request.AddFilter( "secure", "1" );
// AND with the next 1 rule (if not it'll OR)
Request.AddFilter( "and", "1" );
// Show only servers that are the same version
Request.AddFilter( "gametype", GameVersionString );
Request.OnChanges += OnServersUpdated;
Request.RunQueryAsync( 30 );
void OnServersUpdated() {
// No reponsive servers yet, bail
if ( Request.Responsive.Count == 0 )
return;
// Process each responsive server
foreach ( var s in Request.Responsive ) {
ServerResponded( s );
}
// Clear the responsive server list so we don't
// reprocess them on the next call.
Request.Responsive.Clear();
}
void ServerResponded( ServerInfo server ) {
// Do whatever you want with the server information
Log( $"{server.Name} Responded!" );
}
```
--------------------------------
### SteamServerInit ModDir
Source: https://wiki.facepunch.com/steamworks/~pagelist_p=2&sort=
Gets or sets the mod directory for the server.
```APIDOC
## GET or POST /websites/wiki_facepunch_steamworks/SteamServerInit.ModDir
### Description
Retrieves or sets the directory path where game mods are located.
### Method
GET (to retrieve), POST (to set)
### Endpoint
/websites/wiki_facepunch_steamworks/SteamServerInit.ModDir
### Parameters
#### Request Body (for POST)
- **value** (string) - Required - The path to the mod directory.
### Request Example (POST)
```json
{
"value": "./mods/my_mod"
}
```
### Response
#### Success Response (200)
- **modDir** (string) - The current mod directory path.
#### Response Example
```json
{
"modDir": "./mods/my_mod"
}
```
```
--------------------------------
### Access Steamworks Features
Source: https://wiki.facepunch.com/steamworks/Setting_Up~edit
Demonstrates how to access various Steamworks functionalities after successful initialization. This includes retrieving player information like name and Steam ID, triggering screenshots, setting user statistics, and iterating through inventory items and friends lists. The `SteamClient.IsValid` property can be used to check if the client is ready.
```csharp
var playername = SteamClient.Name;
var playersteamid = SteamClient.SteamId;
SteamScreenshots.TriggerScreenshot();
Steamworks.SteamUserStats.SetStat( "deaths", value );
foreach ( var item in Steamworks.SteamInventory.Items ) {
Debug.Log( $"{item.Def.Name} x {item.Quantity}" );
}
foreach ( var player in SteamFriends.GetFriends() ) {
Debug.Log( $"{player.Name}" );
}
```
--------------------------------
### SteamServerInit GamePort
Source: https://wiki.facepunch.com/steamworks/~pagelist_p=2&sort=
Gets or sets the game port for the server.
```APIDOC
## GET or POST /websites/wiki_facepunch_steamworks/SteamServerInit.GamePort
### Description
Retrieves or sets the network port used for game traffic on the server.
### Method
GET (to retrieve), POST (to set)
### Endpoint
/websites/wiki_facepunch_steamworks/SteamServerInit.GamePort
### Parameters
#### Request Body (for POST)
- **value** (integer) - Required - The port number for game traffic.
### Request Example (POST)
```json
{
"value": 27015
}
```
### Response
#### Success Response (200)
- **gamePort** (integer) - The current game port.
#### Response Example
```json
{
"gamePort": 27015
}
```
```
--------------------------------
### Get Steam Avatar Asynchronously (C#)
Source: https://wiki.facepunch.com/steamworks/GetClientAvatarUnity
Retrieves a Steam client's large avatar asynchronously using Facepunch.Steamworks. It includes error handling to log any exceptions during the process. This method returns a nullable Image object.
```csharp
private static async Task GetAvatar() {
try {
// Get Avatar using await
return await SteamFriends.GetLargeAvatarAsync(SteamClient.SteamId);
} catch (Exception e) {
// If something goes wrong, log it
Debug.Log(e);
return null;
}
}
```
--------------------------------
### Initialize Steamworks Client in Unity
Source: https://wiki.facepunch.com/steamworks/Installing_For_Unity
Initializes the Steamworks client with a given application ID. This should be called once during application startup. It throws an exception if initialization fails, potentially due to Steam being closed, missing DLLs, or insufficient permissions.
```csharp
try {
Steamworks.SteamClient.Init( 252490 );
} catch ( System.Exception e ) {
// Something went wrong - it's one of these:
// // Steam is closed?
// // Can't find steam_api dll?
// // Don't have permission to play app?
}
```
--------------------------------
### SteamServer.MaxPlayers
Source: https://wiki.facepunch.com/steamworks/~pagelist_p=1&sort=views
Gets or sets the maximum number of players allowed on the server.
```APIDOC
## SteamServer.MaxPlayers
### Description
Gets or sets the maximum number of players allowed on the server.
### Method
N/A
### Endpoint
SteamServer.MaxPlayers
### Parameters
N/A
### Request Example
N/A
### Response
#### Success Response (200)
- **MaxPlayersValue** (int) - The maximum player count.
#### Response Example
N/A
```
--------------------------------
### C# Socket Server Interface Implementation
Source: https://wiki.facepunch.com/steamworks/Creating_A_Socket_Server~edit
This C# code demonstrates creating a socket server by implementing the `ISocketManager` interface. It defines methods for connection events and message handling. The server is started using `SteamNetworkingSockets.CreateNormalSocket`, passing an instance of a class that implements the interface.
```csharp
public class MyServer : ISocketManager {
public void OnConnecting( Connection connection, ConnectionInfo data ) {
connection.Accept();
Console.WriteLine( $"{data.Identity} is connecting" );
}
public void OnConnected( Connection connection, ConnectionInfo data ) {
Console.WriteLine( $"{data.Identity} has joined the game" );
}
public void OnDisconnected( Connection connection, ConnectionInfo data ) {
Console.WriteLine( $"{data.Identity} is out of here" );
}
public void OnMessage( Connection connection, NetIdentity identity, IntPtr data, int size, long messageNum, long recvTime, int channel ) {
Console.WriteLine( $"We got a message from {identity}!" );
// Send it right back
connection.SendMessage( data, size, SendType.Reliable );
}
}
SocketManager manager = SteamNetworkingSockets.CreateNormalSocket( Data.NetAddress.AnyIp( 21893 ), myServer );
```
--------------------------------
### SteamServerInit SteamPort
Source: https://wiki.facepunch.com/steamworks/~pagelist_p=2&sort=
Gets or sets the Steam communication port for the server.
```APIDOC
## GET or POST /websites/wiki_facepunch_steamworks/SteamServerInit.SteamPort
### Description
Retrieves or sets the network port used for communication with the Steam network.
### Method
GET (to retrieve), POST (to set)
### Endpoint
/websites/wiki_facepunch_steamworks/SteamServerInit.SteamPort
### Parameters
#### Request Body (for POST)
- **value** (integer) - Required - The port number for Steam communication.
### Request Example (POST)
```json
{
"value": 27017
}
```
### Response
#### Success Response (200)
- **steamPort** (integer) - The current Steam communication port.
#### Response Example
```json
{
"steamPort": 27017
}
```
```
--------------------------------
### Steamworks.ServerList.Internet.RunQueryAsync
Source: https://wiki.facepunch.com/steamworks/ServerList.Internet
Asynchronously queries the server list. The task result indicates completion.
```APIDOC
## Steamworks.ServerList.Internet.RunQueryAsync
### Description
Queries the server list. The Task result will be true when finished.
### Method
GET (or equivalent for asynchronous operations)
### Endpoint
/websites/wiki_facepunch_steamworks/api/ServerList.Internet.RunQueryAsync
### Parameters
#### Query Parameters
- **timeoutSeconds** (float) - Optional - The timeout in seconds for the query. Defaults to 10.
### Request Example
(No explicit request body for this type of query, parameters are typically passed as query parameters or implicitly via context)
### Response
#### Success Response (200)
- **Task** - A Task that resolves to a boolean indicating if the query finished successfully.
```
--------------------------------
### SteamServerInit Secure
Source: https://wiki.facepunch.com/steamworks/~pagelist_p=2&sort=
Gets or sets whether the server connection is secure.
```APIDOC
## GET or POST /websites/wiki_facepunch_steamworks/SteamServerInit.Secure
### Description
Retrieves or sets a boolean value indicating whether the server connection uses secure protocols.
### Method
GET (to retrieve), POST (to set)
### Endpoint
/websites/wiki_facepunch_steamworks/SteamServerInit.Secure
### Parameters
#### Request Body (for POST)
- **value** (boolean) - Required - Set to true if the connection is secure, false otherwise.
### Request Example (POST)
```json
{
"value": true
}
```
### Response
#### Success Response (200)
- **secure** (boolean) - The current security status of the server connection.
#### Response Example
```json
{
"secure": true
}
```
```