Advertisement
Pro_Unit

BuyButton

Sep 8th, 2022
798
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.42 KB | None | 0 0
  1. using System;
  2. using AnimalsSimulator.Project;
  3. using TMPro;
  4. using UniRx;
  5. using UnityEngine;
  6. using UnityEngine.UI;
  7. using Zenject;
  8.  
  9. namespace AnimalsSimulator.Common.UI
  10. {
  11.     [RequireComponent(typeof(Button))]
  12.     public class BuyButton : MonoBehaviour
  13.     {
  14.         [SerializeField] private TextMeshProUGUI _priceText;
  15.         [SerializeField] private Button _button;
  16.        
  17.         [Inject] private PurchaseService _purchaseService;
  18.        
  19.         private CompositeDisposable _disposable;
  20.  
  21.         private void OnValidate() => _button ??= GetComponent<Button>();
  22.  
  23.         public IObservable<Unit> BindOnClick(IReadOnlyReactiveProperty<int> price)
  24.         {
  25.             _disposable?.Dispose();
  26.             _disposable = new CompositeDisposable();
  27.  
  28.             price.Subscribe(SetPrice)
  29.                 .AddTo(_disposable);
  30.  
  31.             var reactiveCommand = price.Select(_purchaseService.CanBuy)
  32.                 .Merge(_purchaseService.Money.Select(CanBuy))
  33.                 .ToReactiveCommand();
  34.  
  35.             reactiveCommand.BindToOnClick(_button, _ => _purchaseService.Purchase(price.Value))
  36.                 .AddTo(_disposable);
  37.  
  38.             return reactiveCommand;
  39.  
  40.             bool CanBuy(int money) =>
  41.                 price.Value <= money;
  42.         }
  43.  
  44.         private void SetPrice(int price)
  45.         {
  46.             var text = price.ToString();
  47.  
  48.             _priceText.SetText(text);
  49.         }
  50.     }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement