首页 > 技术文章 > unity 选色板

daluo 2016-08-28 19:13 原文

前段时间做了一个小蛋糕,里面要用到一个选色(左上角那个哦)

 

废话不多说  先上代码

[csharp] view plain copy
 
print?
  1. using UnityEngine;  
  2. using UnityEngine.UI;  
  3. using System.Collections;  
  4.   
  5. public class setColor : MonoBehaviour {  
  6.     public GameObject m;  
  7.     public static setColor _instance;  
  8.     float temp;  
  9.     public Texture2D setCo;  
  10.        
  11.     private RectTransform im;  
  12.     public float _sizeDeltaY;  
  13.   
  14.   
  15.     public float local_V;  
  16.     public float local_y;  
  17.     public float scenceY;  
  18.   
  19.   
  20.     private float   height;  
  21.   
  22.   
  23.   
  24.     private float baifeibi;  
  25.   
  26.     void Awake()  
  27.     {  
  28.         _instance = this;  
  29.     }  
  30.     void Start()  
  31.     {  
  32.         height = Screen.height;  
  33.         im = GetComponent<RectTransform> ();  
  34.         _sizeDeltaY = im.sizeDelta.y;  
  35.         local_V = im.anchoredPosition3D.y;  
  36.         local_y = im.anchoredPosition3D.y + _sizeDeltaY;  
  37.     }  
  38.       
  39.     // Update is called once per frame  
  40.     public void OnMouseDown ()   
  41.     {  
  42.         if (m == null)  
  43.             return;  
  44.         temp = (Input.mousePosition.y - height);  
  45.         baifeibi=(temp - local_V)/_sizeDeltaY;  
  46.         //(int)(baifeibi*setCo.height)  
  47.         Color co= setCo.GetPixel (1,(int)(baifeibi*setCo.height));  
  48.         print ((int)(baifeibi * setCo.height));  
  49.         MeshRenderer[] mrs;  
  50.         mrs = m.GetComponentsInChildren<MeshRenderer>();  
  51.         foreach (var item in mrs)  
  52.         {  
  53.             foreach (Material items in item.materials)  
  54.             {  
  55.                 items.color = co;  
  56.             }  
  57.                
  58.         }  
  59.          
  60.     }  
  61. }  
 

 

首先获取 选色版被点击时的点击坐标相对于选色版本身的百分比

 

然后读取选色版这张图片实际百分比的实际像素

 

获取像素的颜色信息 

 

然后赋值给物体

 

当然这里有个坑  会报无法读写像素的错误  你可以参照下面设个设置图片的属性

 

 

如果你想获取图片的绝对像素信息(选折板这里就是需要绝对坐标)

那么 你的anchors 应该是这样

 

好了 赶紧做一个自己的着色版吧 (这个是一维的 只需要Y轴的百分比    二维的也基本一致需要获取下X轴 )

推荐阅读