Advertisement
ianwexl0rz

Unity - Subtexture Changer

Apr 23rd, 2017
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.17 KB | None | 0 0
  1. /************************************************
  2. | SubtextureChanger.cs
  3. |
  4. | Ian Wexler
  5. |
  6. | Changes the scale and offset of a material's
  7. | texture to show a specific section.
  8. ************************************************/
  9.  
  10. using UnityEngine;
  11.  
  12. public class SubtextureChanger : MonoBehaviour
  13. {
  14.     [SerializeField]
  15.     private Material material = null;
  16.  
  17.     [SerializeField]
  18.     private int columns = 1;
  19.  
  20.     [SerializeField]
  21.     private int rows = 1;
  22.  
  23.     [SerializeField]
  24.     private int index = 0;
  25.  
  26.     private void OnValidate()
  27.     {
  28.         SetSubtexture(index);
  29.     }
  30.  
  31.     public void SetSubtexture(int i)
  32.     {
  33.         // Loop around and filter out negative values.
  34.         int count = columns * rows;
  35.         index = (i % count + count) % count;
  36.  
  37.         Vector2 offset = new Vector2();
  38.         Vector2 scale = new Vector2();
  39.  
  40.         // Set the scale based on rows and columns.
  41.         scale.x = 1 / (float)columns;
  42.         scale.y = 1 / (float)rows;
  43.  
  44.         // Set the offset so the index increases on x and then y.
  45.         offset.x = (index % columns) * scale.x;
  46.         offset.y = (index / columns) * scale.y;
  47.  
  48.         // Apply the scale and offset.
  49.         material.SetTextureScale("_MainTex", scale);
  50.         material.SetTextureOffset("_MainTex", offset);
  51.     }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement