0

I would like to generate meshes and textures procedural in Unity/C#. However all my attempts with a custom mesh only display the first texel. I tried to simplify the problem as much as possible and came up with the following example code, which draws a white square instead of a "polish flag".

using UnityEngine;
using System.Collections;

public class Test : MonoBehaviour {

    [SerializeField] Material unlitMaterial;

    void Start () {
        Mesh mesh = new Mesh();
        mesh.vertices = new Vector3[4] { Vector3.zero, new Vector3 (1, 0, 0), new Vector3 (1, 0, 1), new Vector3 (0, 0, 1) };
        mesh.triangles = new int[6] {1, 0, 3, 2, 1, 3 } ; 
        mesh.RecalculateNormals();

        Texture2D texture = new Texture2D (2, 2);
        texture.SetPixels (new Color[4] {Color.white, Color.white, Color.red, Color.red});
        texture.filterMode = FilterMode.Point;
        texture.Apply();

        GameObject gameObject = new GameObject ();
        MeshRenderer meshRenderer = gameObject.AddComponent<MeshRenderer> ();
        if (unlitMaterial != null)
            meshRenderer.material = unlitMaterial;
        meshRenderer.material.mainTexture = texture;
        gameObject.AddComponent<MeshFilter> ().mesh = mesh;
    }
}

(I tried different materials such as unlit/texture with no effect)

Thanks a lot for any help ;-)

Lunkford
  • 43
  • 5

1 Answers1

0

I think you are missing setting UVs. Check this: Unity3D answers link

since he only has 4 verts, just handset them to (0,0) (0,1) (1,1) and (1,0): uvs[0]=new Vector2(0,0); ....

and set it like this: mesh.uv = uvs;

Jerry Switalski
  • 2,690
  • 1
  • 18
  • 36
  • Thank you! I really forgot the uvs, sorry for the rather stupid question. In case anybody comes across this question, add the following line: mesh.uv = new Vector2[4] { Vector2.zero, new Vector2 (1, 0), new Vector2 (1, 1), new Vector2 (0, 1) }; to make this basic example work. – Lunkford Jun 30 '16 at 10:55