2013-12-16 290 views
2

我正在開發一個使用虛擬按鈕的Vuforia應用程序。我使用的虛擬按鈕的例子,我發現這部分的腳本如何更改Unity中材質的顏色?

public void OnButtonPressed(VirtualButtonBehaviour vb) 
{ 
    Debug.Log("OnButtonPressed"); 

    if (!IsValid()) 
    { 
     return; 
    } 

    // Add the material corresponding to this virtual button 
    // to the active material list: 
    switch (vb.VirtualButtonName) 
    { 
     case "red": 
      mActiveMaterials.Add(m_TeapotMaterials[0]); 
      break; 

     case "blue": 
      mActiveMaterials.Add(m_TeapotMaterials[1]); 
      break; 

     case "yellow": 
      mActiveMaterials.Add(m_TeapotMaterials[2]); 
      break; 

     case "green": 
      mActiveMaterials.Add(m_TeapotMaterials[3]); 
      break; 
    } 

    // Apply the new material: 
    if (mActiveMaterials.Count > 0) 
     mTeapot.renderer.material = mActiveMaterials[mActiveMaterials.Count - 1]; 
} 

正如所看到的,我只是必須在每種情況下添加代碼爲「做一些事情」。那麼,我想做的事情是改變一個對象的顏色。 該對象是從Maya導出的fbx並具有動畫。我想改變對象內部網格的顏色。 該對象被稱爲「路徑」,它內部有3個網格(polySurface1_MeshPart0,..1,.2),每個網格對應於網格的不同部分具有不同的材質,它們是沒有紋理的材質,只是純色着色器漫反射。 我需要改變對象的特定網格中的這些材料之一的顏色:)

任何幫助,高度讚賞。

回答

1

從Unity3D文檔:http://docs.unity3d.com/Documentation/ScriptReference/Material-color.html

您需要通過GameObject.Find必須要麼找到在運行時GameObjects()或將其分配到腳本公共成員。每個網格都應該可以作爲GameObject進行檢索。一旦你有參考有關遊戲對象,你應該能夠訪問它的材料,像這樣:使用提供將代碼

myGameObject.renderer.material.color = Color.Red; 

一個例子:

switch (vb.VirtualButtonName) 
{ 
    case "red": 
     mActiveMaterials.Add(m_TeapotMaterials[0]); 
     GameObject go = GameObject.Find("The Name Of The Object You Are Looking For"); 
     go.renderer.material.color = Color.Red; 
     break; 
} 
+0

感謝您的回答Xerosigma。但我仍然遇到問題,我使用了您提供給我的解決方案,但沒有奏效,我不知道什麼是錯,它只是不會改變顏色。下面是一個截圖工作http://imageshack.com/a/img843/9475/if3b.png – Osuka42

+0

@ Osuka42在紅色的情況下嘗試以下內容:Material [] mats = go.renderer.materials;對於(int i = 0; i

相關問題