如何更改陣列中的一種材料?
我已經將一個 Daz 人物匯入統一,所有材料都存盤在該人物的陣列中。

我正在嘗試通過單擊按鈕來更改鳶尾花的紋理。
下面的代碼確實改變了材料,但只改變了陣列中的第一個材料。我試圖更改代碼以更改 Irises,但我無法做到。
{
//Component
private Renderer _rendereyes;
//Game Object
public GameObject eyes;
//etc
public Object[] texEyes;
public int texID;
// Start is called before the first frame update
void Start()
{
//Get Component
_rendereyes = eyes.GetComponent<Renderer>();
//Change eye tex
string texPath = "Textures";
texEyes = Resources.LoadAll(texPath, typeof(Texture2D));
}
public void SetEyeTexture()
{
if (texID < texEyes.Length - 1)
{
texID ;
}
else
{
texID = 0;
}
_rendereyes.material.SetTexture("_DiffuseMap",(Texture2D)texEyes[texID]);
}
這是代碼的第二次迭代,這是我嘗試更改 Irises 紋理的代碼。
{
//Component
private Renderer[] _rendereyes;
//Game Object
public GameObject eyes;
//etc
public Object[] texEyes;
public int texID;
// Start is called before the first frame update
void Start()
{
//Get Component
_rendereyes = eyes.GetComponent<Renderer[]>();
//Change eye tex
string texPath = "Textures";
texEyes = Resources.LoadAll(texPath, typeof(Texture2D));
}
public void SetEyeTexture()
{
if (texID < texEyes.Length - 1)
{
texID ;
}
else
{
texID = 0;
}
_rendereyes[15].material.SetTexture("_DiffuseMap",(Texture2D)texEyes[texID]);
}
更改 Irises 紋理的最佳方法是什么?
uj5u.com熱心網友回復:
首先,通常完全避免使用Resources。(請參閱最佳實踐 -> 資源)
不要使用它!
然后,如果您使用它,一般來說,我會更具體地做
public Texture2D[] texEyes;
接著
texEyes = Resources.LoadAll<Texture2D>(texPath);
或者更確切地說,只需通過檢查器將它們拖放到插槽中
最后
GetComponent<Renderer[]>
沒有意義。您總是希望獲得單個組件或使用GetComponents.
但是,聽起來您實際上只有一個物件和一個物件,Renderer并且想要堅持
_rendereyes = eyes.GetComponent<Renderer>();
或直接制作
[SerializeField] private Renderer _rendereyes;
并將物件拖到檢查器中的插槽中。
然后寧愿從Renderer.materials.
然后你的SetEyeTexture方法有一點邏輯錯誤。
你做
if (texID < texEyes.Length - 1)
{
texID ;
}
這可能導致texID = texEyes.Lengthwhich 超出范圍,因為在c#所有索引中都從0到array.Length - 1。
您的代碼應該看起來像
public void SetEyeTexture()
{
// Simple modulo trick to get a wrap around index
texID = ( texID) % texEyes.Length;
// Note that according to your screenshot the Material "Irises" is at index 14 not 15!
_rendereyes.materials[14].SetTexture("_DiffuseMap", texEyes[texID]);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/410988.html
標籤:
