LoginSignup
13
20

More than 5 years have passed since last update.

Unity・Rails間のデータ送受信の方法

Last updated at Posted at 2017-04-24

こんにちは。

今回はUnity・Ruby on Rails間のデータ送受信の方法を説明します。

環境

  • Unity 5.6.0f3
  • Rails 5.0

データ送信

データを送信する場合の例です。

Unity側

using UnityEngine.Networking;

    public void ConnectionStart(){
        StartCoroutine(Coneection("str"));
    }

    private IEnumerator Connection(string name)
    {
        WWWForm form = new WWWForm();
        form.AddField("name", name);
        UnityWebRequest request = UnityWebRequest.Post("https://myapp.com", form);

        // リクエスト送信
        yield return request.Send();

        if (request.isError) {
            Debug.Log ("エラー:" + request.error);
        } else {
            if (request.responseCode == 204) {
                Debug.Log ("せいこう!");
            } else {
                Debug.Log ("しっぱい…:" + request.responseCode);
            }
        }
    }

送信するデータはWWWFormクラスのAddFieldメソッドを使って設定します。
yield return request.Send();はUnityのコルーチンという機能を使っています。
ここでは、リクエストの結果が返ってくるまで次の処理に行かないようにしています。
request.responseCodeにはリクエストのHTTPステータスコードが入っています。

ステータスコード一覧はこちら

Rails側

routes.rb
post '/', to: 'top_pages#create'
top_pages_controller.rb
  def create
    puts params[:name]
  end

Railsでは、routes.rbとtop_pages_controller.rbに上記のコードを追加します。
Unity側のform.AddField("name", name);の第1引数と、
Rails側のparams[:name]のシンボルが対応しています。

さらに、Unity側のform.AddField("name", name);の第2引数と、
Rails側のparams[:name]の中身が対応しています。

データ受信

データを受信する場合の例です。

Unity側

using UnityEngine.Networking

    public void ConnectionStart(){
        StartCoroutine(Connection());
    }

    private IEnumerator Connection() {
        UnityWebRequest request = UnityWebRequest.Get("https://myapp.com/show");

        // リクエスト送信
        yield return request.Send();

        if (request.isError) {
            Debug.Log("エラー:" + request.error);
        } else {
            if (request.responseCode == 200) {
                Debug.Log ("せいこう!");
                Debug.Log (request.downloadHandler.text));
            } else {
                Debug.Log ("しっぱい…:" + request.responseCode);
            }
        }
    }

基本的にデータ送信とほとんど変わりません。Railsから受信したデータはrequest.downloadHandler.textに入っています。

Rails側

routes.rb
  get '/show', to: 'top_pages#show'
top_pages_controller.rb
  def show
    render :text "str"
  end

Railsのコードも基本的にデータ送信とほとんど変わりません。
renderを使うことでRailsからUnityにデータを送れます。
ここでは文字列を例にしましたが、文字列以外も送れます。

詳しくはこちらから

何か質問がありましたらお気軽に。

参考

UnityWebRequestによるHTTP通信

13
20
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
13
20