Energy #

Read more about the Energies system in Hiro here.

Initializing the energies system #

The energies system relies on the Nakama System and an ILogger, both must be passed in as dependencies via the constructor.

1
2
var energiesSystem = new EnergiesSystem(logger, nakamaSystem);
systems.Add(energiesSystem);

Subscribing to changes in the energy system #

You can listen for changes in the energy system so that you can respond appropriately, such as updating the UI, by implementing the IObserver pattern, or use the SystemObserver<T> type which handles it for you.

1
2
3
4
5
var disposer = SystemObserver<EnergiesSystem>.Create(energiesSystem, system => {
    Instance.Logger.Info($"System updated.");

    // Update UI elements etc as necessary here...
});

Refreshing the energy system #

To ensure the energy system has the latest information from Nakama you can refresh it.

1
await energiesSystem.RefreshAsync();

Listing available energy #

You can list the available energies for a user.

1
2
3
4
5
6
7
8
foreach (var energyKvp in energiesSystem.Energies)
{
    var name = energyKvp.Key;
    var energy = energyKvp.Value;

    Debug.Log($"Energy {name} ({energy.Current}/{energy.Max})");
    Debug.Log($"Next refill in {(energy.NextRefillTimeSec - energy.CurrentTimeSec) / 1000}s");
}

Spending energy #

You can spend energy as a user, either as a single energy at a time or as multiple at once.

1
2
3
4
5
6
7
8
9
// Spend a single energy
await energiesSystem.SpendEnergyAsync("lives", 1);

// Spend multiple energies
await energiesSystem.SpendEnergyAsync(new Dictionary<string, int>
{
    { "lives", 1 },
    { "hearts", 5 }
});

Granting energy #

While energy can be granted as part of a reward, you can also grant it directly.

1
2
3
4
5
await energiesSystem.GrantAsync(new Dictionary<string, int>
{
    { "lives", 1 },
    { "hearts", 5 }
});