Advertisement
Flynny85

Unity Simple UI Toggle and save

Mar 30th, 2017
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.30 KB | None | 0 0
  1. using UnityEngine;
  2. using UnityEngine.UI;
  3. using UnityEngine.EventSystems;
  4.  
  5. public class UI_Toggle : MonoBehaviour, IPointerClickHandler, IPointerDownHandler, IPointerUpHandler {
  6.  
  7.     public Image _Button;
  8.  
  9.     public Vector3 _Scale_Pressed;
  10.     private Vector3 _Scale_Normal;
  11.  
  12.     public string _prefStringTitle = "prefStringTitle";
  13.  
  14.     public Sprite _ON_Image;
  15.     public Sprite _OFF_Image;
  16.  
  17.     private int _currentValue = 1;
  18.  
  19.     void OnEnable(){
  20.         _currentValue = PlayerPrefs.GetInt ( _prefStringTitle , 1);
  21.         _Scale_Normal = _Button.rectTransform.localScale;
  22.         Toggle_Fire();
  23.     }
  24.  
  25.     public void Toggle_Fire(){
  26.         if (_currentValue == 1) {
  27.             _Button.sprite = _ON_Image;
  28.         } else {
  29.             _Button.sprite = _OFF_Image;
  30.         }
  31.  
  32.         Debug.Log ("Prefs Update: Toggle: " + _prefStringTitle.ToString() + " = " + _currentValue);
  33.  
  34.         PlayerPrefs.SetInt ( _prefStringTitle ,  _currentValue);
  35.         PlayerPrefs.Save();
  36.     }
  37.  
  38.     public void OnPointerDown( PointerEventData eventData )
  39.     {
  40.         _Button.rectTransform.localScale = _Scale_Pressed;
  41.     }
  42.  
  43.     public void OnPointerUp( PointerEventData eventData )
  44.     {
  45.         _Button.rectTransform.localScale = _Scale_Normal;
  46.     }
  47.  
  48.     public void OnPointerClick( PointerEventData eventData )
  49.     {
  50.         if (_currentValue == 1) {
  51.             _currentValue = 0;
  52.         } else {
  53.             _currentValue = 1;
  54.         }
  55.         Toggle_Fire ();
  56.     }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement