Skip to content

Instantly share code, notes, and snippets.

@MuhammadFaizanKhan
Created July 19, 2022 08:18
Show Gist options
  • Save MuhammadFaizanKhan/018dda9aba9f82e4881c04e6082ef985 to your computer and use it in GitHub Desktop.
Save MuhammadFaizanKhan/018dda9aba9f82e4881c04e6082ef985 to your computer and use it in GitHub Desktop.
Unity UI Two State button. Button state will reamin pressed you click on the it.
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
[RequireComponent(typeof(Button))]
[RequireComponent(typeof(Image))]
public class SpriteSwap : MonoBehaviour
{
[Header("Button Start State")]
public bool isPressed;
private Sprite stateNormal;
private Button btnCurrent;
private Image imgCurrent;
private EventSystem myEventSystem;
protected void Start()
{
btnCurrent = GetComponent<Button>();
imgCurrent = GetComponent<Image>();
stateNormal = imgCurrent.sprite;//storing current sprite.
myEventSystem = FindObjectOfType<EventSystem>();
}
public virtual void OnClick()
{
isPressed = !isPressed;
if (isPressed)
{
Debug.Log("Button pressed");
imgCurrent.sprite = btnCurrent.spriteState.pressedSprite;
}
else
{
Debug.Log("Button not pressed");
imgCurrent.sprite = stateNormal;
myEventSystem.SetSelectedGameObject(null);//Deselect the button so it colour changed to normal.
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment