using System.Collections; using UnityEngine; using UnityEngine.UI; using UnityEngine.Events; using UnityEngine.EventSystems; namespace Michsky.UI.Heat { public class SwitchManager : MonoBehaviour, IPointerClickHandler, IPointerEnterHandler, IPointerExitHandler, ISelectHandler, IDeselectHandler, ISubmitHandler { // Resources [SerializeField] private Animator switchAnimator; [SerializeField] private CanvasGroup highlightCG; // Saving public bool saveValue = false; public string saveKey = "My Switch"; // Settings public bool isOn = true; public bool isInteractable = true; public bool invokeOnEnable = true; public bool useSounds = true; public bool useUINavigation = false; [Range(1, 15)] public float fadingMultiplier = 8; // Events [SerializeField] public SwitchEvent onValueChanged = new SwitchEvent(); public UnityEvent onEvents = new UnityEvent(); public UnityEvent offEvents = new UnityEvent(); [System.Serializable] public class SwitchEvent : UnityEvent { } bool isInitialized = false; void Awake() { if (saveValue) { GetSavedData(); } else { if (gameObject.activeInHierarchy) { StopCoroutine("DisableAnimator"); StartCoroutine("DisableAnimator"); } switchAnimator.enabled = true; if (isOn) { switchAnimator.Play("On Instant"); } else { switchAnimator.Play("Off Instant"); } } if (gameObject.GetComponent() == null) { Image raycastImg = gameObject.AddComponent(); raycastImg.color = new Color(0, 0, 0, 0); raycastImg.raycastTarget = true; } if (useUINavigation) { AddUINavigation(); } if (highlightCG == null) { highlightCG = new GameObject().AddComponent(); highlightCG.transform.SetParent(transform); highlightCG.gameObject.name = "Highlighted"; } if (invokeOnEnable && isOn) { onEvents.Invoke(); onValueChanged.Invoke(isOn); } else if (invokeOnEnable && !isOn) { offEvents.Invoke(); onValueChanged.Invoke(isOn); } isInitialized = true; } void OnEnable() { if (UIManagerAudio.instance == null) { useSounds = false; } if (isInitialized) { UpdateUI(); } } void GetSavedData() { if (gameObject.activeInHierarchy) { StopCoroutine("DisableAnimator"); StartCoroutine("DisableAnimator"); } switchAnimator.enabled = true; if (PlayerPrefs.GetString("Switch_" + saveKey) == "" || !PlayerPrefs.HasKey("Switch_" + saveKey)) { if (isOn) { switchAnimator.Play("Off"); PlayerPrefs.SetString("Switch_" + saveKey, "true"); } else { switchAnimator.Play("Off"); PlayerPrefs.SetString("Switch_" + saveKey, "false"); } } else if (PlayerPrefs.GetString("Switch_" + saveKey) == "true") { switchAnimator.Play("Off"); isOn = true; } else if (PlayerPrefs.GetString("Switch_" + saveKey) == "false") { switchAnimator.Play("Off"); isOn = false; } } public void AddUINavigation() { Button navButton = gameObject.AddComponent