Created
July 15, 2020 05:29
-
-
Save HolyFot/40a333299e01a08e32ffa6b055a087c0 to your computer and use it in GitHub Desktop.
Slider Percent UI C# Unity
This file contains hidden or 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
| //Made by: HolyFot | |
| //License: CC0 - https://creativecommons.org/share-your-work/public-domain/cc0/ | |
| //Notes: Handles negative to positive ranges too. | |
| using System; | |
| using UnityEngine; | |
| using UnityEngine.UI; | |
| [RequireComponent(typeof(Slider))] | |
| public class SliderPercent : MonoBehaviour | |
| { | |
| public Slider slider1; | |
| public Text percentText; | |
| public bool showDecibals; | |
| void Awake() | |
| { | |
| slider1 = gameObject.GetComponent<Slider>(); | |
| if (slider1 != null) | |
| slider1.onValueChanged.AddListener(delegate { UpdatePercentText(); }); | |
| } | |
| void UpdatePercentText() | |
| { | |
| if (slider1 == null || percentText == null) | |
| { | |
| Debug.Log("[SliderPercent] Slider or Text not set."); | |
| return; | |
| } | |
| string percent1 = "0%"; | |
| float min = slider1.minValue; | |
| float max = slider1.maxValue; | |
| float currValue = slider1.value; | |
| if (min == 0.0f) min = 0.000001f; | |
| if (currValue == 0.0f) currValue = 0.000001f; | |
| if (max == 0.0f) max = 0.000001f; | |
| //100% | |
| if (Mathf.Approximately(currValue, max) && !showDecibals) | |
| { | |
| percentText.text = "100%"; | |
| return; | |
| } | |
| if (showDecibals) //Decibals | |
| percent1 = currValue.ToString("0.00") + " dB"; | |
| else //Positive/Negative Ranges | |
| { | |
| float range1 = max - min; | |
| float value = Math.Abs((currValue - min) / range1 * 100f); | |
| percent1 = value.ToString("0") + "%"; | |
| } | |
| percentText.text = percent1; | |
| } | |
| public bool CompareFloats(float a1, float b1) | |
| { | |
| float t1 = 0.1f; | |
| return System.Math.Abs(a1 - b1) < t1; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment