Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using UnityEngine;
- using UnityEngine.UI;
- [RequireComponent(typeof(Image))]
- [ExecuteInEditMode]
- public class SubstanceController : MonoBehaviour
- {
- private const string ShaderName = "UI/Substance";
- public const string PercentageProperty = "_Percentage";
- private Image image;
- private void Awake()
- {
- image = GetComponent<Image>();
- if (image.material.shader.name != ShaderName)
- {
- Debug.LogError("Bad shader on image material attached!");
- }
- }
- // Use this method for instant substance percentage fill change
- public void ChangePercentage(float toValue)
- {
- image.material.SetFloat(PercentageProperty, Mathf.Clamp(toValue, 0.0f, 1.0f));
- }
- // Use this method for substance percentage fill change in time
- public void ChangePercentageInTime(float toValue, float time)
- {
- // clamping values to match range defined in shader
- StartCoroutine(ChangeValueInMaterial(Mathf.Clamp(toValue, 0.0f, 1.0f), PercentageProperty, time));
- }
- private IEnumerator ChangeValueInMaterial(float toValue, string propertyName, float time)
- {
- float startingValue = image.material.GetFloat(propertyName);
- float curTime = 0.0f;
- while (curTime <= time)
- {
- curTime += Time.deltaTime;
- image.material.SetFloat(propertyName, Mathf.Lerp(startingValue, toValue, curTime / time));
- yield return null;
- }
- image.material.SetFloat(propertyName, toValue);
- yield return null;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement