我动态创建预制件并尝试在子GameObject上设置一堆属性。其中一个属性是纹理,虽然纹理确实显示为预制件的子节点(与GameObject和Mesh相同),GameObject上的MeshRenderer仍然没有显示任何材质,整个网格显示为粉红色。这是我的代码:
Texture2D sharedTexture = (Texture2D)Resources.Load ("mainTexture", typeof(Texture2D));
string prefabPath = basepath + filename + ".prefab";
UnityEngine.Object prefab = PrefabUtility.CreateEmptyPrefab (prefabPath);
GameObject root = new GameObject ("Zone_" + filename);
GameObject temp = new GameObject(filename);
Texture2D texCopy = (Texture2D)UnityEngine.Object.Instantiate (sharedTexture);
MeshFilter meshFilter = (MeshFilter)temp.AddComponent<MeshFilter> ();
MeshRenderer meshRenderer = temp.AddComponent<MeshRenderer> ();
MeshCollider meshCollider = (MeshCollider)temp.AddComponent<MeshCollider> ();
temp.AddComponent<Zone> ();
Mesh mesh = buildMeshForFilename (filename);
mesh.name = "Zone_Mesh";
meshFilter.mesh = mesh;
meshCollider.sharedMesh = mesh;
meshRenderer.material.mainTexture = texCopy;
temp.transform.parent = root.transform;
AssetDatabase.AddObjectToAsset(mesh, prefabPath);
AssetDatabase.AddObjectToAsset (texCopy, prefabPath);
PrefabUtility.ReplacePrefab(root, prefab, ReplacePrefabOptions.ConnectToPrefab);
AssetDatabase.SaveAssets ();
GameObject.Destroy (root);
如何在网格上显示纹理,所以它不仅仅是粉红色?
答案 0 :(得分:0)
好的,解决了。对于任何绊脚石的人的未来参考,我通过做以下事情来修复它:
我删除了对Texture2D(sharedTexture和texCopy)的引用。然后我将我的png拖到编辑器中的一个游戏对象上,生成一个Material并将其放入它创建的Materials文件夹中。然后我使用AssetDatabase加载该材料,如下所示:
Material mainMat = (Material)AssetDatabase.LoadAssetAtPath ("Assets/resources/Materials/mainTexture.mat", typeof(Material));
然后我将该材质直接分配给MeshRenderer,如下所示:
meshRenderer.material = mainMat;
这似乎已经足够了。