コード例 #1
0
    private GameObject GenerateMesh(GameObject container, Tiles[,] map, Vector2 position, Tiles tileType, string tag)
    {
        GameObject meshContainer = new GameObject("mesh-tiles-" + tileType.ToString());

        meshContainer.tag = tag;
        meshContainer.transform.parent = container.transform;
        //Generate Mesh
        MeshFilter   meshFilter   = meshContainer.AddComponent <MeshFilter>();
        MeshRenderer meshRenderer = meshContainer.AddComponent <MeshRenderer>();

        Mesh mesh = MeshGenerator.GenerateSquaredMesh(MapUtils.ConvertMap(map), 1, (int)tileType);

        meshFilter.mesh = mesh;
        meshFilter.transform.position = position;

        //Texturise mesh
        int size = 55;

        Texture2D texture = new Texture2D(size * map.GetLength(0), size * map.GetLength(1));

        //List<Color[]> tilesTextures = new List<Color[]>();
        //foreach (var tileTexture in textures)
        //{
        //    tilesTextures.Add(tileTexture.GetPixels(0, 0, size, size));
        //}

        for (int x = 0; x < map.GetLength(0); x++)
        {
            for (int y = 0; y < map.GetLength(1); y++)
            {
                if (map[x, y] == tileType)
                {
                    string textureForTile = MapUtils.GetTileSpriteName(map, x, y);
                    texture.SetPixels(x * size, y * size, size, size, mapTextures[textureForTile].GetPixels());
                    //texture.SetPixels(x * size, y * size, size, size, tilesTextures[Random.Range(0, tilesTextures.Count)]);
                }
            }
        }

        texture.filterMode = FilterMode.Point;
        texture.wrapMode   = TextureWrapMode.Clamp;
        texture.Apply();

        Material material = new Material(Shader.Find("Sprites/Diffuse"));

        material.color       = Color.white;
        material.mainTexture = texture;

        meshRenderer.material = material;
        return(meshContainer);
    }