-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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