7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Unity WebAPIを使ってデータを扱う

Last updated at Posted at 2020-03-17

環境

PHP(Laravel5)
Unity 2019.1.4f1 (64-bit)

概要

WebAPIを使った通信とデータ扱い。
・UnityWebRequest
APIのリクエストするため

・JsonUtility
APIで取得したjsonを使うため

この二点を使う。

実装

Model.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking; 

public class Model 
{
	public int id;
	public int name;
	public int hp;

	string access_url = "https://hoge.com/api/v1";

	[System.Serializable]
	public class Character
	{
		public int id;
		public string name;
		public int hp;
	}

	[System.Serializable]
	public class Characters
	{
		public Character[] characters;
	}

	public IEnumerator ApiRequest()
	{
		UnityWebRequest request = UnityWebRequest.Get(access_url);
		request.SetRequestHeader("Content-Type", "application/json");
		yield return request.SendWebRequest();

		Characters characters = JsonUtility.FromJson<Characters>("{\"characters\":" + request.downloadHandler.text + "}");

		id = characterClass.characters[0].id;
		name = characterClass.characters[0].name;
		hp = characterClass.characters[0].hp;	
	}
}

使い方

読み込まれた時点で呼びだしてあげればいいかと思います。
後は好みでどうぞ

	public void Start()
	{
		StartCoroutine(getModel());
	}

	IEnumerator getModel()
	{
		characterModel = new CharacterModel(); 
		yield return StartCoroutine(characterModel.ApiRequest());
                // 以下表示させるなど
	}

PHP - Laravel

特別なことはしてない
LaravelのModelを読んでreturnで返すだけです。

namespace App\Http\Controllers;
use App\Models\Character;

class ApiController extends Controller
{
    public function index()
    {
        return Character::all();
    }
}
7
6
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
7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?