2015-11-12 37 views
3

我正在完成我正在放置資產商店的資產。現在,其中一個功能需要精靈的平均顏色。現在我有一個公共顏色來查找平均顏色,用戶可以使用顏色選擇器或色輪或其他來選擇他們認爲看起來像精靈的平均顏色。我想這樣做,腳本自動計算平均精靈顏色,因此通過消除人爲錯誤提高精度,並通過不浪費用戶猜測平均精靈顏色的時間來提高效率。如何獲得精靈的平均顏色? (Unity3d)

回答

4

那麼在Unity論壇中有一篇關於它的文章。 Here的鏈接。答案是:

Color32 AverageColorFromTexture(Texture2D tex) 
{ 

     Color32[] texColors = tex.GetPixels32(); 

     int total = texColors.Length; 

     float r = 0; 
     float g = 0; 
     float b = 0; 

     for(int i = 0; i < total; i++) 
     { 

      r += texColors[i].r; 

      g += texColors[i].g; 

      b += texColors[i].b; 

     } 

     return new Color32((byte)(r/total) , (byte)(g/total) , (byte)(b/total) , 0); 

} 
+0

好了,我嘗試這樣做: TransitionColor = AverageColorFromTexture(gameObject.GetComponent ()sprite.texture); 我收到一條錯誤消息,說明紋理不可讀。 – user3738071

+1

@ user3738071在編輯器中的Inspector的設置中將紋理標記爲可讀(您將不得不將紋理類型切換爲_Advanced_) – Roberto