Unity安卓端运行时创建MeshFilter模型变粉(编辑器正常)
Hey there, let’s walk through the issues in your code and fix that annoying pink mesh problem—pink usually means Unity can’t find a valid material or mesh to render, so let’s break it down step by step:
Key Issues in Your Code
1. Missing Mesh Assignment to MeshFilter
You added a MeshFilter component but never created or assigned a Mesh object to it. The Unity Editor might use a fallback placeholder for unassigned meshes, but Android’s runtime doesn’t have this safety net—so it renders pink instead of your intended geometry.
2. Empty, Invalid Texture
Creating a texture with new Texture() gives you a completely blank, uninitialized texture with no pixel data. Desktop GPUs might tolerate this lazy workaround, but Android’s GPU will reject it outright, leading to broken material rendering.
3. Redundant & Unsafe Component Calls
You already have direct references to renderer and filter, but you’re calling GetComponent<MeshFilter>() and GetComponent<MeshRenderer>() again. This is unnecessary, wastes performance, and can cause unexpected behavior if components are modified later.
Fixed Code Example
Here’s a revised version that addresses all these issues, using a simple quad mesh and a valid cross-platform material:
// Add components and store direct references (no redundant GetComponent calls) MeshRenderer renderer = gameObject.AddComponent<MeshRenderer>(); MeshFilter filter = gameObject.AddComponent<MeshFilter>(); // Create a basic quad mesh (replace this with your custom vertex/triangle data if needed) Mesh quadMesh = new Mesh(); Vector3[] vertices = new Vector3[] { new Vector3(-0.5f, -0.5f, 0), new Vector3(0.5f, -0.5f, 0), new Vector3(0.5f, 0.5f, 0), new Vector3(-0.5f, 0.5f, 0) }; int[] triangles = new int[] { 0, 1, 2, 0, 2, 3 }; quadMesh.vertices = vertices; quadMesh.triangles = triangles; quadMesh.RecalculateNormals(); // Assign the mesh to the MeshFilter (critical for rendering) filter.mesh = quadMesh; // Create a valid unlit white material (no empty texture required) Material whiteMaterial = new Material(Shader.Find("Unlit/Color")); whiteMaterial.color = Color.white; renderer.material = whiteMaterial; // Set scale using the existing filter reference filter.transform.localScale = new Vector3(0.0009f, 0.0009f, 0.0009f);
Additional Android Compatibility Tips
- Skip dynamic empty resources: Never use
new Texture()or uninitialized meshes—always provide valid vertex/texture data, or use pre-made assets from your Project folder. - Stick to built-in shaders: Shaders like
Unlit/ColororStandardare guaranteed to work across platforms; custom shaders may need Android-specific adjustments for GPU compatibility. - Verify build inclusion: Ensure any textures or materials you use are marked as included in the build (Unity might strip unused assets during Android packaging, breaking dynamic references).
内容的提问来源于stack exchange,提问作者DannyFar94

