Unity で Parse.com を使う - 初期化からユーザー登録とユーザーログインまで
はじめに
- Unity で MBaaS である Parse.com を使ったアプリの作成から、ユーザーの登録とユーザーログインまでを行ったメモ。
Parse.com の登録とアプリの作成
- Parse.com への登録は https://www.parse.com/ の Sign Up から。
- ユーザー登録をすると、そのままアプリの作成になる。
- Quickstart Guide から Date を選択、Unity を選択、New Project を選択で、Parse SDK が組み込み済みの Unity のプロジェクトをダウンロードできる。
- Quickstart > Data > Unity > Existing Project を選択すると、Parse SDK のダウンロードリンクと、Parse SDK のイニシャライザーの GameObject の作り方を案内される。
ユーザー登録
コード
- NGUI の InputField から文字列を取得して登録処理を実行する。
- ParseUser 初期化時に渡す Username は一意であることが保証され、重複があるとエラーとなり、error.Message で "400 Bad Request\r" が返る。
- ParseUser 初期化時に Email も渡すことが可能であり、これも一意であることが保証される。
- SignUpAsync() で登録リクエストを送信し、レスポンスが返ってきたタイミングで、ContinueWith() の中のコールバックが実行される。
- ContinueWith() のコールバック処理内では Find や GetComponent などが実行できないため、エラー発生時には ErrorMessage という一時変数にエラーを入れて、Update() などで表示する。
public void SignUp () { if (ParseUser.CurrentUser != null) { Debug.Log(ParseUser.CurrentUser["username"] + " is already logged in"); return; } string username = UsernameInputField.GetComponent<UIInput>().value; string password = PasswordInputField.GetComponent<UIInput>().value; ParseUser user = new ParseUser() { Username = username, Password = password }; try { user.SignUpAsync().ContinueWith(t => { if (t.IsFaulted) { // Errors from Parse Cloud and network interactions using (IEnumerator<System.Exception> enumerator = t.Exception.InnerExceptions.GetEnumerator()) { if (enumerator.MoveNext()) { ParseException error = (ParseException) enumerator.Current; // error.Message will contain an error message // error.Code will return "OtherCause" Debug.Log(error.Message); Debug.Log(error.StackTrace); ErrorMessage = error.Message; } } } else { Debug.Log(ParseUser.CurrentUser["username"] + " is signed up."); } }); } catch (InvalidOperationException e) { ErrorMessage = e.Message; Debug.Log(e.Message); } }
ユーザーログイン
コード
- ユーザー登録と同様に NGUI の InputField から文字列を取得してログイン処理を実行する。
public void LogIn () { if (ParseUser.CurrentUser != null) { Debug.Log(ParseUser.CurrentUser["username"] + " is already logged in"); return; } string username = UsernameInputField.GetComponent<UIInput>().value; string password = PasswordInputField.GetComponent<UIInput>().value; ParseUser.LogInAsync(username, password).ContinueWith(t => { if (t.IsFaulted || t.IsCanceled) { // Errors from Parse Cloud and network interactions using (IEnumerator<System.Exception> enumerator = t.Exception.InnerExceptions.GetEnumerator()) { if (enumerator.MoveNext()) { ParseException error = (ParseException) enumerator.Current; // error.Message will contain an error message // error.Code will return "OtherCause" Debug.Log(error.Message); ErrorMessage = error.Message; } } } else { Debug.Log(ParseUser.CurrentUser["username"] + " is logged in."); } }); }