今回は、Unityでスコアランキング(オンラインランキング)を簡単に実装してみます。
見た目は一旦置いといて、どのように実装するのかを簡単にやってみます。
はじめに
オンラインランキングや対戦型のゲームなどを実装する場合、自分でサーバーを立てるか、外部サービスを利用するかが必要になります。
手軽なのはもちろん外部サービスを使う方法。ということで今回はNCMB(ニフクラモバイルバックエンド)を利用して簡単にランキングを実装してみます。
サービスの登録
まずは登録。今回使うのはニフクラのmBaaS(mobile backend as a Service)です。
無料プランはSNS連携で登録、私はGoogleアカウントでログインしました。

メール確認が届くのでクリックすれば登録完了。10秒もあればできますね。
ログインすると、初めに「アプリの新規作成」画面が出てくるので、名前を適当につけておきます。

Unityで実装開始
登録が済んだらUnityを起動、今回は新規で作成してみます。
Unityのバージョンは2021.3.3f1。

Unityの起動を待つ間に必要なSDKをダウンロードしておきます。
下記のGithubのページから最新のZipファイルをダウンロード。

Unityが起動したら、ダウンロードしたSDKを取り込み(ダブルクリック)。

全てのファイルをインポート。

サンプルを確認
インポートしたファイルの中にあるサンプルを動かしてみます。
Scenes→QuickStartフォルダ内にあるQuickStartシーンに切り替えます。
その中のNCMBSettingsにアプリケーションキーとクライアントキーを入力します。

入力するキーは管理画面の「アプリ設定」内にあります。

キーを入力したら実行をしてみます。実行すると下記のスクリプトが動きます。

サンプルスクリプト通りにデータストアにデータが入ればOK

ランキングの実装
ここからランキングを実装していきます。
新規シーンに切り替え。NCMBManagerとNCMBSettingsのプレハブをヒエラルキーメニューに入れます

NCMBSettingsにキーを入力。

空オブジェクトを追加、名前をScoreManagerとしてScoreSaveスクリプトをアタッチ。

ScoreSaveスクリプトは下記に変更。サンプルと同じ感じですが、通信が発生するので未接続の可能性も考慮して少し処理を追加。パラメータに指定した値をデータストアに保存する感じです。
using System.Collections; using System.Collections.Generic; using UnityEngine; using NCMB; public class ScoreSave : MonoBehaviour { public void SaveScore(int Score) { NCMBObject scoreClass = new NCMBObject("ScoreClass"); scoreClass["score"] = Score; scoreClass.SaveAsync((NCMBException e) => { if (e != null) { Debug.Log("Error: " + e.ErrorMessage); } else { Debug.Log("success"); } }); } }
UI→ボタンを追加。

ボタンクリックでスコアを追加するようにします。実際はゲーム終了時に呼び出す感じですかね。

実行してみて、コンソールにsuccessと表示され、スコアが保存されていればOK。

次は保存したスコアの呼び出し、ScoreManagerオブジェクトにScoreLoadで新規スクリプトをアタッチ。

スクリプトは下記に変更。スコアを高い順に10件と指定してからデータを抜き出しています。
using System.Collections; using System.Collections.Generic; using UnityEngine; using NCMB; public class ScoreLoad : MonoBehaviour { public void LoadScore() { int rank; NCMBQuery<NCMBObject> query = new NCMBQuery<NCMBObject>("ScoreClass"); query.OrderByDescending("score"); query.Limit = 10; query.FindAsync((List<NCMBObject> objList, NCMBException e) => { if (e != null) { Debug.LogWarning("error: " + e.ErrorMessage); } else { for (int i = 0; i < objList.Count; i++) { rank = i + 1; Debug.Log("ScoreRanking " + rank + "位: " + objList[i]["score"]); } } }); } }
同じようにボタンを作成して、呼び出し。

コンソールに表示されるか確認。

次に、適当に複数のスコアを保存してから実行、スコアの大きい順に並んで表示されればOK。

実際には10番目のスコアを取得して、そのスコアよりも上だったらデータストアに保存する感じにするのかな。
この後は画面を作って、取得したスコアを表示って感じですね。ユーザー名の入力・表示もあった方が良いですかね。
とりあえず今回はスコアの保存と呼び出しまで。
無料枠について
無料で使える枠はAPIリクエストが月10万回まで。他にも条件がありますが十分すぎるかなと。

並び替えや件数絞りではリスクエスト回数は増えないみたい。
ランキング以外にもアイテムを管理したりガチャ機能もできるみたい。
オフラインランキング
ちなみに、自分の端末内だけでランキングするならplayerprefsで良いかな。