Tournaments - Code
[SOCL-Tournaments-03]
Initialize BeamContext
This code sample is very similar to most other code guides. Note that we are saving the User ID to a variable for use in later functions.
private BeamContext _beamContext;
private long _userId;
private async void Start()
{
_beamContext = BeamContext.Default;
await _beamContext.OnReady;
_userId = _beamContext.PlayerId;
Debug.Log($"User Id: {_userId}");
}
Get Tournaments
This function will return all tournaments in your game's content database.
private async Task<List<TournamentInfo>> GetTournaments()
{
var response = await _beamContext.Api.TournamentsService.GetAllTournaments();
return response?.tournaments;
}
Join Tournament
Before a score can be posted in a tournament, the player must join the tournament using this function.
private async Task JoinTournament(string tournamentId)
{
await _beamContext.Api.TournamentsService.JoinTournament(tournamentId);
}
Set Score
The following function sets the user's score in the tournament. The _userId
variable comes from BeamContext in the "Initialize BeamContext" example above.
private async Task SetScore(string tournamentId, double score)
{
await _beamContext.Api.TournamentsService.SetScore(tournamentId, _userId, score);
}
Sample Code
Beamable SDK Examples
• The following example code is available for download at GitHub.com/Beamable_SDK_Examples
using Beamable.Common.Tournaments;
using UnityEngine;
namespace Beamable.Examples.Services.TournamentService
{
/// <summary>
/// Demonstrates <see cref="TournamentService"/>.
/// </summary>
public class TournamentServiceExample : MonoBehaviour
{
[SerializeField] private TournamentRef _tournamentRef = null;
[SerializeField] private double _score = 100;
protected void Start()
{
Debug.Log("Start()");
TournamentsSetScore(_tournamentRef.GetId(), _score);
}
private async void TournamentsSetScore(string id, double score)
{
var beamContext = BeamContext.Default;
await beamContext.OnReady;
var userId = beamContext.PlayerId;
Debug.Log($"beamContext.PlayerId = {userId}");
// Need to fetch the status for the current tournament cycle in order to set the score.
var current = await beamContext.Api.TournamentsService.GetTournamentInfo(id);
// This allows the currently logged in user to join the tournament by its content id.
await beamContext.Api.TournamentsService.JoinTournament(current.tournamentId, 0);
// Let's set the score for this player!
await beamContext.Api.TournamentsService.SetScore(current.tournamentId, userId, score);
Debug.Log($"Tournaments.SetScore({id},{userId},{score})");
}
}
}
Updated 11 months ago