Advertisement
Guest User

Untitled

a guest
Mar 17th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.60 KB | None | 0 0
  1. using System.Collections;
  2.  
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5.  
  6. [RequireComponent(typeof(Image))]
  7. [ExecuteInEditMode]
  8. public class SubstanceController : MonoBehaviour
  9. {
  10.  
  11.     private const string ShaderName = "UI/Substance";
  12.     public const string PercentageProperty = "_Percentage";
  13.  
  14.     private Image image;
  15.     private void Awake()
  16.     {
  17.         image = GetComponent<Image>();
  18.  
  19.         if (image.material.shader.name != ShaderName)
  20.         {
  21.             Debug.LogError("Bad shader on image material attached!");
  22.         }
  23.     }
  24.  
  25.     // Use this method for instant substance percentage fill change
  26.     public void ChangePercentage(float toValue)
  27.     {
  28.         image.material.SetFloat(PercentageProperty, Mathf.Clamp(toValue, 0.0f, 1.0f));
  29.     }
  30.  
  31.     // Use this method for substance percentage fill change in time
  32.     public void ChangePercentageInTime(float toValue, float time)
  33.     {
  34.         // clamping values to match range defined in shader
  35.         StartCoroutine(ChangeValueInMaterial(Mathf.Clamp(toValue, 0.0f, 1.0f), PercentageProperty, time));
  36.     }
  37.  
  38.     private IEnumerator ChangeValueInMaterial(float toValue, string propertyName, float time)
  39.     {
  40.         float startingValue = image.material.GetFloat(propertyName);
  41.  
  42.         float curTime = 0.0f;
  43.         while (curTime <= time)
  44.         {
  45.             curTime += Time.deltaTime;
  46.             image.material.SetFloat(propertyName, Mathf.Lerp(startingValue, toValue, curTime / time));
  47.             yield return null;
  48.         }
  49.  
  50.         image.material.SetFloat(propertyName, toValue);
  51.         yield return null;
  52.     }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement