Skip to main content

ログイン

 

ポップアップ表示の練習実験

PHPのスクリプトを呼び出し、結果を Debug.Log で表示してみましょう。

APIを作成

固定結果を確認

UnityでAPIと接続

Awaitable とは

非同期処理について

UnityからWebサーバーへの依頼:UnityWebRequest

APIクラスを作成

// ログインの結果
public struct LoginResponse
{
    // 成功したか?
    public bool success;
}

// サーバーに依頼するメソッドの一覧
public static class APIRequest 
{
    // サーバーのAPIのURL
    private const string ServerAPI = "http://localhost/api";
    
    // 非同期処理:ログイン
    // user:ユーザー名
    // password:パスワード
    public static async Awaitable<LoginResponse> LoginAsync(string user, string password)
    {
        // POSTでデータを送るので、フォームを用意する
        // サーバーが期待しているデータに合わせる
        var postData = new WWWForm();
        postData.AddField("user", user);
        postData.AddField("pass", password);
        
        // ログインAPIのURLへリクエストを送信
        const string url = ServerAPI + "/login.php";
        var webRequest = UnityWebRequest.Post(url, postData);
        
        // 返事を待機する
        await webRequest.SendWebRequest();

        // 返事の文字列を取得
        var webResponse = webRequest.downloadHandler.text;
        
        // デバッグ用
        // Debug.Log(webResponse); 
        
        // JSONから使えるデータにする
        return JsonUtility.FromJson<LoginResponse>(webResponse);
    }
}

if文で確認

データベースを作成

API処理を更新