2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【GCP/Unity】Unity から Google Cloud の API を叩く基本的な流れ

Last updated at Posted at 2024-12-23

はじめに

テスト環境

  • IDE
    • Unity:6000.0.25f1
    • Visual Studio 2022:17.11.5
  • プラグイン等
    • UniTask:2.5.10
    • NuGetForUnity:4.1.1
    • Google.Apis.Auth:1.68.0

手順

サービスアカウントの作成

手順1

以下の記事などを参考にして Google アカウントの作成や無料トライアルへの登録、プロジェクトの作成などの Googe Cloud の初期設定を行う。

手順2

Google Cloud にアクセスして「IAM と管理>サービスアカウント」に行き、「サービスアカウントを作成」を押す。

TSUBASAMUSU.png

手順3

「サービスアカウント名」と「サービスアカウント ID」を入力して「作成して続行」を押す。

TSUBASAMUSU.png

手順4

必要に応じて「ロールを選択」を押してロールを選択し、「続行」を押す。

例:Cloud Storage のオブジェクトを読み取る場合は「Cloud Storage > Storage オブジェクト閲覧者」など

TSUBASAMUSU.png

手順5

必要に応じて「サービスアカウントユーザーロール」と「サービスアカウント管理者ロール」を設定して「完了」を押す。

TSUBASAMUSU.png

秘密鍵のダウンロード

手順6

作成したサービスアカウントを選択して「キー>鍵を追加>新しい鍵を作成」を押す。

TSUBASAMUSU.png

手順7

「キーのタイプ」で「JSON」を選択して右下の「作成」を押し、JSON ファイルをダウンロードする。

TSUBASAMUSU.png

依存関係のインポート

手順8

UniTaskNuGetForUnity の最新版のリリースを GitHub からダウンロードし、Assets フォルダ内で右クリックして「Import Package > Custom Package...」を選択し、ダウンロードした .unitypackage ファイルをインポートする。

TSUBASAMUSU.png

手順9

エディタ上部の「NuGet > Manage NuGet Packages」を選択して NuGet のウィンドウを開く。

TSUBASAMUSU.png

手順10

検索窓に「google api」等と入力して「Search」を押し、「Google.Apis.Auth」の「Install」を押してインストール完了後にウィンドウを閉じる。

TSUBASAMUSU.png

API の使用(Cloud Translation API の場合)

手順11

Google Cloud に戻り、使用したい API の「有効にする」を押す。

TSUBASAMUSU.png

手順12

Unity にて、Google Cloud の API を叩く際に必要なアクセストークンを取得する以下のような関数を作成する。

GetGoogleCloudJwtAsync()
/*
using Cysharp.Threading.Tasks;
using Google.Apis.Auth.OAuth2;
using System;
using System.IO;
using System.Text;
*/
public static async UniTask<string> GetGoogleCloudAccessTokenAsync(TextAsset serviceAccountJsonFile, string[] scopes)
{
    try
    {
        if (serviceAccountJsonFile == null || string.IsNullOrEmpty(serviceAccountJsonFile.text))
        {
            Debug.LogError("The service account JSON file is not set or empty.");

            return string.Empty;
        }

        byte[] jsonData = Encoding.UTF8.GetBytes(serviceAccountJsonFile.text);

        using MemoryStream memoryStream = new(jsonData);

        GoogleCredential googleCredential = GoogleCredential.FromStream(memoryStream).CreateScoped(scopes); ;

        if (googleCredential.IsCreateScopedRequired)
        {
            Debug.LogError("The provided credentials are not valid for generating JWT.");

            return string.Empty;
        }

        return await ((ServiceAccountCredential)googleCredential.UnderlyingCredential).GetAccessTokenForRequestAsync();
    }
    catch (Exception exception)
    {
        Debug.LogException(exception);

        return string.Empty;
    }
}

手順13

API ドキュメントを確認しながら API を叩く関数を作成する。
ヘッダーの「Authorization」に Google Cloud 用のアクセストークンを渡してあげるのがポイント。
(以下は Cloud Translation API の例)

  • 構造体
    • リクエスト
      Request.cs
      using System;
      
      [Serializable]
      public struct Request
      {
          public string[] q;
      
          public string target;
      }
      
    • レスポンス
      Response.cs
      using System;
      
      [Serializable]
      public struct Response
      {
          public Data data;
      }
      
      Data.cs
      using System;
      
      [Serializable]
      public struct Data
      {
          public Translation[] translations;
      }
      
      Translation.cs
      using System;
      
      [Serializable]
      public struct Translation
      {
          public string translatedText;
      
          public string detectedSourceLanguage;
      }
      
  • 関数
    GetTranslatedTextAsync()
    /*
    using Cysharp.Threading.Tasks;
    using System;
    using System.Collections.Generic;
    using System.Text;
    using UnityEngine;
    using UnityEngine.Networking;
    */
    
    public static async UniTask<Response> GetTranslatedTextAsync(string googleCloudAccessToken, string[] sourceTexts, string targetLanguageCode)
    {
        Dictionary<string, string> headers = new()
        {
            {
                "Content-type",
                "application/json"
            },
            {
                "Authorization",
                "Bearer " + googleCloudAccessToken//アクセストークンを渡す
            }
        };
    
        Request request = new()
        {
            q = sourceTexts,
            target = targetLanguageCode
        };
    
        using UnityWebRequest unityWebRequest = new("https://translation.googleapis.com/language/translate/v2", "POST")
        {
            uploadHandler = new UploadHandlerRaw(Encoding.UTF8.GetBytes(JsonUtility.ToJson(request))),
            downloadHandler = new DownloadHandlerBuffer()
        };
    
        foreach (KeyValuePair<string, string> header in headers)
        {
            unityWebRequest.SetRequestHeader(header.Key, header.Value);
        }
    
        try
        {
            await unityWebRequest.SendWebRequest();
        }
        catch (Exception exception)
        {
            Debug.LogException(exception);
    
            return new();
        }
    
        if (unityWebRequest.result != UnityWebRequest.Result.Success)
        {
            Debug.LogError(unityWebRequest.error);
    
            return new();
        }
    
        return JsonUtility.FromJson<Response>(unityWebRequest.downloadHandler.text);
    }
    

手順14

実際に API を叩いて動作を確認する。
アクセストークンを発行する際に、API ドキュメントに書かれている必要なスコープを渡してあげるのがポイント。

Start()
private async void Start()
{
    string[] scopes =
    {
        "https://www.googleapis.com/auth/cloud-translation"
    };

    //サービスアカウントの秘密鍵を作成した際にダウンロードした JSON ファイルを serviceAccountJsonFile 変数に入れる
    string googleCloudAccessToken = await GetGoogleCloudAccessTokenAsync(serviceAccountJsonFile, scopes);

    string[] sourceTexts =
    {
        "Hello world",
        "My name is Tsubasamusu."
    };

    Response response = await GetTranslatedTextAsync(googleCloudAccessToken, sourceTexts, "de");

    Debug.Log(JsonUtility.ToJson(response));
}

最後に

参考記事

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?