Generated mesh is completely black

I have created a script that will generate a square face for a 2D game I am working on, the only thing is that when i assign a material to it it shows completely black no matter the color.

I suspect I need to correctly apply uv coordinates and normals and all that but I don’t know how to do that. can someone help me out I

using UnityEngine;
using System.Collections.Generic;

public class LevelGrid : MonoBehaviour
{
    public Transform parent;

    public int levelWidth = 256;
    public int levelHeight = 128;
    public int edgeBuffer = 8;

    [HideInInspector]
    public List<Vector3> levelGrid;

    void Start()
    {
        GenerateLevelgrid();
        GenerateLevel();
    }

    public void GenerateLevelgrid()
    {
        for (int x = 0; x <= levelWidth; x++)
        {
            for (int y = 0; y <= levelHeight; y++)
            {
                Vector2 gridPoint = new Vector2(x, y);
                levelGrid.Add(gridPoint);
            }
        }
    }

    public void GenerateLevel()
    {
        foreach (Vector3 gridPoint in levelGrid)
        {
            GameObject tileObject = new GameObject();

            tileObject.transform.name = ("Tile(" + gridPoint.x + ", " + gridPoint.y + ")");
            tileObject.transform.parent = parent;
            tileObject.transform.position = gridPoint;

            tileObject.AddComponent<MeshFilter>();
            tileObject.AddComponent<MeshRenderer>();

            Mesh mesh = new Mesh();

            Vector2 vertexOne = new Vector2(-0.5f, 0.5f);
            Vector2 vertexTwo = new Vector2(0.5f, 0.5f);
            Vector2 vertexThree = new Vector2(-0.5f, -0.5f);
            Vector2 vertexFour = new Vector2(0.5f, 0.5f);
            Vector2 vertexFive = new Vector2(-0.5f, -0.5f);
            Vector2 vertexSix = new Vector2(0.5f, -0.5f);

            Vector3[] vertices =
            {
                    vertexOne,
                    vertexTwo,
                    vertexThree,
                    vertexFour,
                    vertexFive,
                    vertexSix
            };

            mesh.vertices = vertices;

            int[] triangles =
            {
                    0, 1, 2,
                    5, 4, 3,
            };

            mesh.triangles = triangles;

            tileObject.GetComponent<MeshFilter>().mesh = mesh;
        }
    }
}

try calling “RecalculateNormals” on your mesh after you are done assigning its points and triangles

4 Likes

Worked for me

Worked for me as well :slight_smile:

RecalculateNormals for every child worked for me. Thank you passerbycmc!

I have a similar problem but with a 3d mesh. I tried recalculate normals( I called it once using a bool) and it did make the mesh bright again, but when I move the mouse back over the scene view it turns dark again! Any ideas ???