duck

Adjust car UV map from atlas based on ID

May 15th, 2012
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.09 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4.  
  5. public class AdjustUV : MonoBehaviour {
  6.    
  7.     public Vector2 tiles = Vector2.one;
  8.     public int index = -1;
  9.     public bool adjusted;
  10.    
  11.     void Awake() {
  12.         index = -1;
  13.         adjusted = false;
  14.     }
  15.    
  16.     void Update() {
  17.         if (!adjusted) {
  18.             Adjust();
  19.             adjusted = true;
  20.         }
  21.        
  22.     }
  23.    
  24.     void Adjust () {
  25.    
  26.         if (index == -1)
  27.         {
  28.             Car car = GetComponent<Car>();
  29.             if (car != null)
  30.             {
  31.                 index = car.id;
  32.             }
  33.         }
  34.        
  35.         int tileX = (index % (int)tiles.x);
  36.         int tileY = Mathf.FloorToInt(index / tiles.x);
  37.         float shiftX = (1 / tiles.x) * tileX;
  38.         float shiftY = (1 / tiles.y) * tileY;
  39.        
  40.         Vector2 shift = new Vector2( shiftX, shiftY );
  41.        
  42.         var meshes = new List<Mesh>();
  43.        
  44.         foreach (Transform t in GetComponentsInChildren<Transform>())
  45.         {
  46.             MeshFilter mf = t.GetComponent<MeshFilter>();
  47.             if (mf != null)
  48.             {
  49.                 Vector2[] uv = mf.mesh.uv;
  50.                 for (int n=0; n<uv.Length; ++n)
  51.                 {
  52.                     uv[n] += shift;
  53.                 }
  54.                 mf.sharedMesh.uv = uv;
  55.                 meshes.Add(mf.sharedMesh);
  56.             }
  57.         }      
  58.     }
  59.    
  60. }
Advertisement
Add Comment
Please, Sign In to add comment