Help us understand the problem. What is going on with this article?

uGUIで動的にサムネイルを生成する

やりたいこと

  • ステージ一覧で、ステージマップのサムネイルを動的に生成して張りつけたい。
    • 一覧される各要素は、動的に生成され、レイアウトグループで配置されます。
  • uGUIで、動的にSpriteを生成してImageに貼り付けます。

やったこと

  • サムネイルの生成は時間がかかるので、非同期に行います。
  • 個々のサムネイルを自律的に生成させます。
private IEnumerator MakeThumbnail () {
    this.Loading.SetActive (true); // クルクルを表示
    this.Thumbnail.gameObject.SetActive (false); // サムネを非表示
    yield return null;
    var size = Mathf.Max (this.Level.Width, this.Level.Height); // 縦横大きい方
    var dx = (size - this.Level.Width) / 2; // 中央寄せのため横のパディング
    var dy = (size - this.Level.Height) / 2; // 中央寄せのため縦のパディング
    this.Texture2D = new Texture2D (size, size); // テクスチャを生成
    for (var y = 0; y < size; y++) {
        for (var x = 0; x < size; x++) {
            var color = this.Level.Matrix [x - dx, y - dy].Color; // 色を取得 (範囲外は自動判別)
            this.Texture2D.SetPixel (x, size - 1 - y, color); // 色を描き込む
            yield return null;
        }
    }
    this.Texture2D.Apply ();
    this.Texture2D.filterMode = FilterMode.Point;
    this.Thumbnail.sprite = this.Sprite = Sprite.Create (this.Texture2D, new Rect (0, 0, size, size), new Vector2 (0.5f, 0.5f));
    this.Thumbnail.gameObject.SetActive (true); // サムネイルを表示
    this.Loading.SetActive (false); // クルクルを非表示
}

// 自分が消えるときには、作ったデータも消す
private void OnDestroy () {
    if (this.Texture2D) { Destroy (this.Texture2D); }
    if (this.Sprite) { Destroy (this.Sprite); }
}

環境

  • unity 2018.4.0f1
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away