9
8

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 5 years have passed since last update.

UniRxでAsyncReactiveCommandを使ったダブルクリックの抑制

Posted at

###背景
最近AsyncReactiveCommandを知ったので使ってみた

###参考
http://neue.cc/2016/08/03_536.html
https://qiita.com/soi/items/eca0601ad0fc4e401623

##問題
ボタンをダブルクリックされても処理は一回だけに抑制したい!

##ボタンひとつの場合

Hoge.cs
	[SerializeField] private Button _button;

	void Start(){
		var asyncReactiveCommand = new AsyncReactiveCommand();
		asyncReactiveCommand.Subscribe(_ => Observable.Timer(TimeSpan.FromSeconds(0.5f)).AsUnitObservable());
		asyncReactiveCommand.BindTo(_button);
	}

これでクリックされてから0.5秒間 interactable を false にしてくれる!

HogeHoge.cs
	[SerializeField] private Button _button;

	void Start(){
		_button.BindToOnClick(_ => {
			return Observable.Timer(TimeSpan.FromSeconds(0.5f)).AsUnitObservable();
		});
	}

これでも同様に動く便利なショートカット!

##ボタン複数の場合
同じグループのボタンでどれか一つでもクリックされたらそのグループのボタンを押させたくない時!

Common.cs

public static class Common
{
	private static readonly Dictionary<int, AsyncReactiveCommand> _asyncReactiveCommandDict = new Dictionary<int, AsyncReactiveCommand>();
	
	public static AsyncReactiveCommand GetAsyncReactiveCommand(int groupId)
	{
		if (_asyncReactiveCommandDict.ContainsKey(groupId))
			return _asyncReactiveCommandDict[groupId];

		_asyncReactiveCommandDict.Add(groupId,new AsyncReactiveCommand());
		_asyncReactiveCommandDict[groupId].Subscribe(_ => Observable.Timer(TimeSpan.FromSeconds(0.5f)).AsUnitObservable());
		return _asyncReactiveCommandDict[groupId];
	}
}
SuppressionDoubleClick.cs
public class SuppressionDoubleClick : MonoBehaviour
{
	[SerializeField] private int _groupId;

	void Start()
	{
		Common.GetAsyncReactiveCommand(_groupId).BindTo(GetComponent<Button>());
	}
}

こんな感じに定義して抑制したいボタンに SuppressionDoubleClick を設定すればおk!
button.gif

思ったより簡単だった

9
8
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
9
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?