5. Spend stamina when starting a quest

Spend stamina on each quest and wait for recovery when it runs low.

Let’s make quests cost stamina. Starting Forest exploration costs 5; if you have less, you must wait for it to recover.

Before you start

Complete any active quest before adding the stamina settings.

Settings to add

Name the stamina setting stamina. Both its initial value and normal recovery limit are 20. Spent stamina recovers naturally by 1 every 300 seconds.

Steps

Create the stamina table

Add Stamina under Add features, then create the following row in Tables → Stamina (Energy).

FieldValue
IDstamina
Initial maximum (defaultMaximum)20
Allow overflow (useOverflow)Off
Overflow maximum (overflowedMaximum)20
Recovery interval (recoveryIntervalMinutes)5 minutes
Recovery amount (recoveryValue)1

The recovery interval is entered in minutes. Enter 5 for a 300-second interval.

Stamina settings: maximum 20, no overflow, recovery of 1 every 5 minutes

Double-click Start costs for forest in Quest (Quest). Open Add item → Not set and select ConsumeStaminaByUserId (consume stamina). Leave Target resource at None and enter the following values.

FieldValue
namespaceNameEnergy
staminaNamestamina
userId#{userId}
consumeValue5

Quest starting cost: consumeValue 5 from stamina in Energy

Keep chapter 3’s normal clear reward: deposit 10 coins into slot 0 in Currency.

Deploy to GS2 and update Unity.

Download AdventureStudioView.cs for this chapter and replace Assets/AdventureStudioView.cs.

Add EnergyHandler to the Gs2 object in Unity, set Id to stamina, and assign it to Energy on AdventureStudioView.

DrawPlayerStatus() displays the current values, including stamina updated by the handler.

private void DrawPlayerStatus()
{
    GUILayout.Label(wallet.HasValue
        ? "Coins: " + wallet.Model.Free
        : "Loading coins...");

    if (!progress.HasValue)
    {
        GUILayout.Label("Loading progress...");
    }
    else
    {
        GUILayout.Label(progress.Model.InProgress
            ? "Adventure in progress"
            : "Choose an adventure");
    }

    GUILayout.Label(energy.HasValue
        ? "Stamina: " + energy.Model.CurrentValue
        : "Loading stamina...");
}

Update the settings

Download the chapter 5 template. Open Deploy → adventure-game → Update stack and select it under Template data. This complete template includes the previous resources. Review and apply the changes, then wait for Update complete.

The template uses the stamina values below. recoverIntervalMinutes is in minutes, so write 5, not 300.

staminaModels:
  - name: stamina
    initialCapacity: 20
    isOverflow: false
    maxCapacity: 20
    recoverIntervalMinutes: 5
    recoverValue: 1

Configure the starting cost as Gs2Stamina:ConsumeStaminaByUserId, with staminaName = stamina and consumeValue = 5. Unity’s Start button still calls the same StartAsync() as in chapter 3.

Update the Unity code

Put these two files in Assets, replacing files with the same names.

Keep the existing Inspector settings.

The relevant part of the script is shown below. You do not need to add this excerpt as another class.

var meter = Gs2.Stamina.Namespace("adventure-stamina").Me(Session).Stamina("stamina");
var subscription = await meter.SubscribeWithInitialCallAsync(value => Stamina = value);

This callback updates the display after stamina is spent or purchased. For natural recovery, call the SDK’s PredictRecovery() when drawing. Display its returned value so stamina increases on screen while you wait.

using Gs2.Unity.Gs2Stamina.Model;

var now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
    + (player.Session.AccessToken.TimeOffset ?? 0) * 1000L;
var stamina = player.Stamina.PredictRecovery(now);
GUILayout.Label("Stamina: " + stamina.Value + " / " + stamina.MaxValue);

now is a millisecond timestamp aligned with the session’s clock. PredictRecovery() returns the recovered value without changing the original data received by the subscription.

What you do

If a quest is in progress, clear it first. Then start the agent in your working folder and give it the following request. When the agent finishes, try the checks under “What to check” below yourself.

Request for the agent

In this folder, I am building a small adventure game with GS2 and Unity.
The GS2 project is adventure, the region is ap-northeast-1,
and I have already signed in.
This folder contains the GS2 Studio project Adventure
and the Unity project AdventureUnity.
So far, I have built login, the quest list (Forest exploration),
and starting and clearing quests with a coin reward (10 free coins per clear).

This time, I want to add stamina.
- The stamina identifier is stamina. It starts at 20, and the maximum is also 20.
  It can never go above the maximum. It recovers by 1 every 5 minutes.
- Starting Forest exploration uses 5 stamina.
- Show the current stamina on the screen (for example, "Stamina 15 / 20")
  and the time left until it next recovers.
- When stamina is too low, the quest cannot be started,
  and the screen makes it clear that stamina is too low.
Keep everything built so far working.
Deploy to GS2 and update Unity, then enter Play Mode in Unity to check that it works.

When you are done, write the steps for me to check the result and a list of the numbers
you chose, without technical terms. If there is anything you did not try, list that too.

What to check

Check by playing: In addition to “Try spending stamina” and “Check what happens when stamina is too low” below, try the following. Where the sections below say that an error should appear, the check passes if the Start button becomes unavailable and the screen makes it clear that stamina is too low.

  • If you wait five minutes without clicking anything, stamina goes up by 1 and the countdown starts again from five minutes
  • At 20 stamina, it does not go any higher
  • At 4 stamina, you cannot start the quest, and the screen makes it clear that stamina is too low. Stamina does not go down either
  • After you restart Play Mode, stamina continues from where it was

Check that the numbers are what you intended

  • The stamina list in the agent’s report (maximum, recovery interval, amount recovered each time, and amount used by Forest exploration) matches the request

Check by asking the agent

  • “Does GS2 calculate stamina recovery? Or does the game’s code add to it?”
  • “When stamina is too low, do you only disable the Start button? Does GS2 also reject the request?”
  • “What did you not try?”

Practice

Ask the agent, “Change the stamina used by Forest exploration to 8.” Once the change is applied, start a new quest and check that stamina goes down by 8. If nothing changes, wait about five minutes, then start a new quest again. When you are done, ask the agent to change it back to 5.

If something goes wrong

  • Check Unity’s Console for red errors. If there are any, paste the message to the agent and ask it to fix the problem.
  • Check what the agent’s report lists as not tried.
  • If you have just changed the settings, wait five minutes, then start a new quest to check.

Try spending stamina

Use the same player as before. After deployment, cost settings can take up to five minutes to take effect. If stamina does not decrease yet, clear the quest, wait a little, and start a new one to check.

  1. Check that stamina is at least 5 and note its current value.
  2. Start Forest exploration and check that stamina drops by 5: for example, from 20 to 15.
  3. Clear the quest and check that you receive 10 coins too.

If stamina recovered between actions, include that recovery when comparing the values.

Practice: change the settings

Try changing the quest’s stamina cost to 8. In Studio, change consumeValue in the starting cost; with the SDK, change consumeValue in the template. Set it to 8 and deploy.

With at least 8 stamina, start Forest exploration and check that it drops by 8. If you have less, wait for natural recovery. If it still drops by 5, clear that quest, wait a little, and start another. After checking, clear the quest, restore the cost to 5, and deploy. Keep the normal reward at 10 coins.

Check what happens when stamina is too low

Wait five minutes after deploying the restored cost, then start a new Forest exploration. Check that it costs 5 stamina, clear it, and then use up enough stamina to test the shortage.

  1. Start and clear Forest exploration until stamina is below 5.
  2. Click Start again. An error should appear, and the quest should not begin.
  3. Check that this failed attempt did not spend any stamina.

Stamina recovers by 1 every 300 seconds. You can start another quest once it reaches 5.

Next: Restore stamina with coins