Search Unity

I create a mesh in code, but it's not visible

Discussion in 'Scripting' started by XTRA_THICC, Feb 6, 2020.

  1. XTRA_THICC

    XTRA_THICC

    Joined:
    Feb 6, 2020
    Posts:
    3
    I have a method which creates a GameObject. It actually creates an object, you can select it in the hierarchy, but you can't actually see it in game, like it has no material.

    Here's the method:

    Code (CSharp):
    1.     void test()
    2.     {
    3.         float length = 0.7f;
    4.         GameObject temp = new GameObject();
    5.         Mesh mesh = new Mesh();
    6.         Material mat = new Material(Shader.Find("Unlit/Color"));
    7.  
    8.         var vertices = new Vector3[4]
    9.         {
    10.             new Vector3(0, 0, 0),
    11.             new Vector3(length, 0, 0),
    12.             new Vector3(0, length, 0),
    13.             new Vector3(length, length, 0)
    14.         };
    15.  
    16.         mesh.vertices = vertices;
    17.         mat.color = Color.magenta;
    18.  
    19.         temp.AddComponent<MeshFilter>();
    20.         temp.AddComponent<MeshRenderer>();
    21.         temp.GetComponent<MeshFilter>().mesh = mesh;
    22.         temp.GetComponent<Renderer>().material = mat;
    23.         temp.GetComponent<Renderer>().enabled = true;
    24.         Instantiate(temp, new Vector2(1, 1), Quaternion.identity);
    25.     }
    Maybe someone could help me out?
     
  2. jvo3dc

    jvo3dc

    Joined:
    Oct 11, 2013
    Posts:
    1,520
    You forgot to add the triangles.
    Code (csharp):
    1.  
    2. mesh.triangles = new int[] { 0, 1, 2, 2, 1, 3 };
    3.  
    (Which you should do after assigning the vertices.)
     
  3. XTRA_THICC

    XTRA_THICC

    Joined:
    Feb 6, 2020
    Posts:
    3
    Still no bueno. The square is not pink as it should be. Maybe something's wrong with the material?
     
  4. jvo3dc

    jvo3dc

    Joined:
    Oct 11, 2013
    Posts:
    1,520
    I don't know. How does it look now?
     
  5. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    Screenshots are very helpful for mesh issues.