1
0

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 1 year has passed since last update.

Unity CancellationToken

Posted at

スクロールのリスト要素を使いまわして使う系のスクローラーで、
スクロール中に画像を読み込む場合のサンプル処理。

SampleCell.cs
using System.Threading.Tasks;
using System.Threading;
using UnityEngine;
using UnityEngine.UI;
using Cysharp.Threading.Tasks;


public class SampleCell : MonoBehaviour {
	// リスト要素データ用クラス
	public class Data {
		public int memberId;
	}

	// キャラアイコン
	[SerializeField] Image _memberIcon;

	private Data _data;
	private CancellationTokenSource _cts = null;


	/// <summary>
	/// リスト要素のデータ設定
	/// </summary>
	public async void SetData(Data data) {
		_data = data;

		// 表示更新
		UpdateView();

		await Task.CompletedTask;
	}

	/// <summary>
	/// 表示更新
	/// </summary>
	private async void UpdateView() {
		// キャンセル
		_cts?.Cancel();
		// CancellationTokenSource生成
		_cts = CancellationTokenSource.CreateLinkedTokenSource(this.GetCancellationTokenOnDestroy());

		try {
			// 読み込み完了までImageを非表示
			_memberIcon.gameObject.SetActive(false);
			// 画像を読み込み (※AppliResourceManagerは独自で用意しているもの)
			Sprite sprite = await AppliResourceManager.Instance.LoadAssetAsync<Sprite>($"asset_bundle/path/{_data.memberId}", _cts.Token);
			// 読み込んだ画像をImageに設定
			_memberIcon.sprite = sprite;
			// Imageを表示
			_memberIcon.gameObject.SetActive(true);
		} catch (System.OperationCanceledException e) {
			// 画像読み込みがキャンセルされた場合
		}
	}
}

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?