Guest User

SetShaderValues.cs

a guest
Mar 17th, 2019
1,032
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class SetShaderValues : MonoBehaviour
  6. {
  7.  
  8.     MaterialPropertyBlock props;
  9.     [SerializeField]
  10.     Transform target;
  11.     float value = 0;
  12.     [SerializeField]
  13.     float appearSpeed = 10f;
  14.     [SerializeField]
  15.     float disappearSpeed = 5f;
  16.     [SerializeField]
  17.     float radius = 12f;
  18.     [SerializeField]
  19.     bool keep = false;
  20.  
  21.     [SerializeField]
  22.     MeshRenderer[] objects;
  23.     [SerializeField]
  24.     float[] values;
  25.     int shaderID;
  26.     // Start is called before the first frame update
  27.     void Start()
  28.     {
  29.         props = new MaterialPropertyBlock();
  30.         for (int i = 0; i < objects.Length; i++)
  31.         {
  32.             objects[i].SetPropertyBlock(props);
  33.         }
  34.         values = new float[objects.Length];
  35.         shaderID = Shader.PropertyToID("_Moved");
  36.  
  37.     }
  38.  
  39.     // Update is called once per frame
  40.     void Update()
  41.     {
  42.         for (int i = 0; i < objects.Length; i++)
  43.         {
  44.             Vector3 offset = objects[i].transform.position - target.position;
  45.             float sqrLen = offset.sqrMagnitude;
  46.             if (sqrLen < radius * radius)
  47.             {
  48.                 values[i] = Mathf.Lerp(values[i], 1, Time.deltaTime * appearSpeed);
  49.             }            
  50.             else if (!keep)
  51.             {
  52.                 values[i] = Mathf.Lerp(values[i], 0, Time.deltaTime * disappearSpeed);
  53.             }
  54.             props.SetFloat(shaderID, values[i]);
  55.             objects[i].SetPropertyBlock(props);
  56.         }
  57.            
  58.  
  59.     }
  60. }
RAW Paste Data