Unity toggle sprite swap for on-off sprites
Unity default toggle component doesn’t have ability to just toggle two images for on/off state.
So here my simple component to do this. It is based on Unity.UI.Button.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
using System; using UnityEngine; using UnityEngine.UI; [RequireComponent(typeof(Button))] public class ToggleSpriteSwap: MonoBehaviour { [SerializeField] private Image targetImage; [SerializeField] private Sprite onSprite; [SerializeField] private Sprite offSprite; [SerializeField] private bool isOn; public bool IsOn { get { return isOn; } set { isOn = value; UpdateValue(); }} public event Action<bool> onValueChanged; private Button button; // to set initial value and skip onValueChanged notification public void Initialize(bool value) { isOn = value; UpdateValue(false); } // Use this for initialization void Start () { button = GetComponent<Button>(); button.transition = Selectable.Transition.None; button.onClick.AddListener(OnClick); } void OnClick() { isOn = !isOn; UpdateValue(); } private void UpdateValue(bool notifySubscribers = true) { if(notifySubscribers && onValueChanged != null) onValueChanged(isOn); if (targetImage == null) return; targetImage.sprite = isOn ? onSprite : offSprite; } } |
Feel free to use it, credits will be nice, but not crucial for this simple peace of code.
: Новости игровой индустрии
- Capcom представила коллекционное издание Resident Evil Village стоимостью почти 140 тысяч рублей
- HITMAN III получит трассировку лучей не только на ПК, но и на PS5 и Xbox Series
- Microsoft отменила повышение цены на Xbox Live Gold, а также сообщила об изменениях касательно f2p-проектов
- Шейдер "эффект Матрицы"
- Обзор Hitman 3: Прощальное турне киллера
- По слухам, Capcom перезапустила разработку ремейка Resident Evil 4
- В Steam состоялся релиз фантастического экшена Orange Cast
- Resident Evil VILLAGE: итоги шоукейса
- Devolver Digital опровергли слух о появлении Fall Guys: Ultimate Knockout в сервисе Xbox Game Pass
Понравилась статья? Поделиться с друзьями: