我在Ressorce文件夹中有一个名为“Walls”的文件夹,它包含多个纹理,调用“wallRoi [1-26]”。现在我想通过C#脚本将它们应用到Unity中的模型中。 解释我的代码:模型有整个墙的多个分段,每个分区都有一个标签(“Wall [1-26]”)。整个墙壁的标签是“墙”。现在我试图在整个墙上循环,并在墙上的每个分段中应用与文件夹不同的纹理。我的准则不起作用,用途如何?谢谢!
private UnityEngine.Object[] walltextures;
void mapTexturesOverWalls() {
walltextures = Resources.LoadAll ("Walls", typeof(Texture2D));
Texture2D[] wallTex = (Texture2D)walltextures [walltextures.Length];
GameObject walls = GameObject.FindGameObjectWithTag ("Wall");
Renderer[] renders = walls.GetComponentsInChildren<Renderer> ();
for (int i = 0; i < wallTex.Length; i++) {
foreach (Renderer r in renders) {
r.material.mainTexture = wallTex[i];
UnityEngine.Debug.Log (wallTex + "");
}
}
}
答案 0 :(得分:3)
创建一个名为TexturesOverWall.cs的新脚本然后复制并粘贴以下代码。您需要做的就是为每个墙分割游戏对象命名,并使用与要应用的纹理相同的名称。希望这能帮助你:)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TexturesOverWall : MonoBehaviour
{
private Texture2D[] walltextures;
void Awake ()
{
mapTexturesOverWalls ();
}
void mapTexturesOverWalls ()
{
walltextures = Resources.LoadAll<Texture2D> ("Walls");
GameObject walls = GameObject.FindGameObjectWithTag ("Wall");
Renderer[] renders = walls.GetComponentsInChildren<Renderer> ();
foreach (Renderer r in renders) {
// all you need to do is name each wall segmentation gameobject with the same name of the texture to apply
r.material.mainTexture = getTextureByName(r.gameObject.name);
}
}
Texture2D getTextureByName (string name)
{
foreach (var tex in walltextures) {
if (tex.name == name)
return tex;
}
return null;
}
}