Search Unity

  1. Click here to receive a gift with your purchase of Unity Pro or Unity Enterprise.
    Dismiss Notice
  2. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice

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,445
    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,445
    I don't know. How does it look now?
     
  5. StarManta

    StarManta

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