This guide is adapted from our Reconstructing Fun video series, where we explore how to build popular game mechanics using Nakama and Hiro. You can watch the full video below and follow our channel on YouTube for the latest updates.
Creating an in-game store that captivates and delights players is a key aspect of modern game design, but creating a store that resonates with players as well as overcomes the technical challenges associated with app store integrations and purchase validation can be a challenge.
In this guide, we’ll explore how to use the economy system to build your in-game store by configuring the available items, integrating them into your game’s UI, managing player purchases, and ensuring they receive their rewards seamlessly.
Once that’s out of the way, you can familiarize yourself with the full project code we’ll be using in this guide by cloning the In-game Store repository from GitHub.
Next we define our InitModule function, which is called when the server starts up. Here we’ll initialize the Hiro systems - Economy and Inventory - we’ll be using, and register the RPC functions we’ll be implementing.
funcInitModule(ctxcontext.Context,loggerruntime.Logger,db*sql.DB,nkruntime.NakamaModule,initializerruntime.Initializer)error{props,ok:=ctx.Value(runtime.RUNTIME_CTX_ENV).(map[string]string)if!ok{returnerrors.New("invalid context runtime env")}env,ok:=props["ENV"]if!ok||env==""{returnerrors.New("'ENV' key missing or invalid in env")}hiroLicense,ok:=props["HIRO_LICENSE"]if!ok||hiroLicense==""{returnerrors.New("'HIRO_LICENSE' key missing or invalid in env")}binPath:="hiro.bin"systems,err:=hiro.Init(ctx,logger,nk,initializer,binPath,hiroLicense,hiro.WithEconomySystem(fmt.Sprintf("base-economy-%s.json",env),true),hiro.WithInventorySystem(fmt.Sprintf("base-inventory-%s.json",env),true))iferr!=nil{returnerr}returnnil}
Next we define the Hiro system definitions we’ll be using to implement the stores in our game. These are defined in the base-inventory-dev1 file and base-economy-dev1 file respectively.
The Hiro Inventory system enables you to define and manage the items that can be collected and used by players in your game. In this example, we’ll use the Inventory system to define the various store item rewards that players can acquire when they make a purchase in the in-game store, setting attributes like their name, category, and maximum count.
The Hiro Economy system enables you to define and manage the currencies that players can earn and spend in your game, and also define the currencies and amounts that each player begins the game with.
Here we define the currencies and amounts that each player begins the game with. We also define the various store items available for purchase, including cosmetic skins and weighted table loot boxes (called Chests in this example).
This file bootstraps our game with a list of systems to be used, and provides a list of systems for deterministic start-up. In our case, we’re initializing the Inventory and Economy core systems from Hiro.
1
2
3
4
5
6
7
8
9
10
11
12
13
// ...systems.Add(nakamaSystem);// Add the Inventory systemvarinventorySystem=newInventorySystem(logger,nakamaSystem);systems.Add(inventorySystem);// Add the Economy systemvareconomySystem=newEconomySystem(logger,nakamaSystem,EconomyStoreType.Unspecified);systems.Add(economySystem);returnTask.FromResult(systems);// ...
The InGameStoreManager manages all calls to our Hiro systems, and creates system observers for each system to handle UI updates based on system changes.
// ...publicasyncTaskInitAsync(){// Get the Economy system and listen for updates._nakamaSystem=this.GetSystem<NakamaSystem>();_economySystem=this.GetSystem<EconomySystem>();SystemObserver<EconomySystem>.Create(_economySystem,OnEconomySystemChanged);// Refresh both systems to get the latest data.awaitTask.WhenAll(_nakamaSystem.RefreshAsync(),_economySystem.RefreshAsync());}privatevoidOnEconomySystemChanged(EconomySystemsystem){// Update coins and gems display._coinsText.text=$"{system.Wallet["coins"]:n0}";_gemsText.text=$"{system.Wallet["gems"]:n0}";// Clear existing shop items from UI.foreach(Transformchildin_storeGroupLarge){Destroy(child.gameObject);}foreach(Transformchildin_storeGroupSmall){Destroy(child.gameObject);}// Update shop items in UI.varlargeStoreItemCategories=new[]{"cosmetics"};foreach(variteminsystem.StoreItems.OrderBy(x=>x.Name)){varisLargeStoreItem=largeStoreItemCategories.Contains(item.Category);varprefab=isLargeStoreItem?_storeItemLargePrefab:_storeItemSmallPrefab;varparent=isLargeStoreItem?_storeGroupLarge:_storeGroupSmall;varstoreItem=Instantiate(prefab,parent);varcost=item.Cost.Currencies.First();storeItem.Init(item.Category,item.Id,item.Name,cost.Key,int.Parse(cost.Value));storeItem.OnClick+=OnStoreItemClick;}}privateasyncvoidOnStoreItemClick(stringitemId){try{varpurchaseAck=await_economySystem.PurchaseStoreItemAsync(itemId);await_economySystem.RefreshAsync();_rewardPanel.Show(new[]{purchaseAck.Reward});}catch(Exception){_errorPanel.SetActive(true);}}// ...