LoginSignup
12
11

More than 5 years have passed since last update.

UnityからTwitterAPIを呼ぶ。UniRxを使って。(2016/9/28追記あり)

Last updated at Posted at 2016-09-27

Twitterアイコン画像をUnityで表示する

Twitter API でタイムラインを持ってくるのだが、そのタイムライン中に含まれているアイコン画像のURLを使って、ランタイムで読み込んで画面に表示してみる。

まず、https://api.twitter.com/1.1/statuses/home_timeline.json を使えば、TwitterタイムラインのJSONが返ってくる。それをパースすると、複数のユーザー情報が集まる。そしてその中のユーザーごとのアイコンのURLを一個一個呼び出して、画像に貼るってことをすればいけると。

ソース

というわけで、一部ソースを抜粋すると、以下のようになる。

ObservableWWW.Get(url, headers)
    .OnErrorRetry((System.Exception ex) => Debug.LogError(ex), System.TimeSpan.FromSeconds(3))
    .Select(jsonText =>
        {
            IList<object> tlList = Json.Deserialize (jsonText) as IList<object>;
            string filePath = "";
            foreach( var oneLine in tlList ) {
                var obj = oneLine as Dictionary<string, object>;
                var user = obj["user"] as Dictionary<string, object>;
                filePath = user["profile_image_url_https"] as string;
                Debug.Log( "img:" + filePath );
                // 本来ここで、次のストリームに行きたい
            }
            return filePath;
        })
    .SelectMany(x => ObservableWWW.GetWWW(x))
    .Retry(3)
    .Select(myWWW => 
        {
            // 本来ここでインスタンス化するけど、、、
            myRender.sharedMaterial.mainTexture = myWWW.texture;
        })
    .Subscribe(_ => Debug.Log( "done" ),ex => Debug.LogException( ex )
    );


なんか違う気がする。

課題

上だと1個のURLしかストリームに流せていないが、複数流せないのか?
つまり、イメージとしては以下の感じ。

IMG_6935.JPG

とりすーぷさんからのリプライ(2016/9/28追記)

その後、Twitterでとりすーぷさんから、超ありがたいリプライが!ありがとうございます!

あ、

Twitter2.cs
ObservableWWW.Get(url, headers)
    .OnErrorRetry((System.Exception ex) => Debug.LogError(ex), System.TimeSpan.FromSeconds(3))
    .Subscribe(jsonText =>
        {
            IList<object> tlList = Json.Deserialize (jsonText) as IList<object>;
            foreach(oneLine in tlList) {
                var obj = oneLine as Dictionary<string, object>;
                var user = obj["user"] as Dictionary<string, object>;
                ObservableWWW.GetWWW(user["profile_image_url_https"] as string)
                  .Retry(3)
                  .Subscribe(result => {
                    //ここで処理
                  });
            }
        });

なるほど!

つまり、Subscribeの中でさらにSubscribeしちゃっていいわけだ。てっきり絶対悪かとおもっていたので、意外な対処法だった。

ちゃんと動いた!とりすーぷさん、ありがとうございます!

12
11
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
12
11