• Advertisement
Sign in to follow this  

Render submesh with material of mesh by script.

Recommended Posts


I want to create a fairly large "tilemap" with 3D assets. I started testing and have very promising results with generating the terrain mesh by code.

private Mesh createChunck(int width, int height)
        Vector3[] verts = new Vector3[width * height * 6];
        Vector2[] uvs = new Vector2[width * height * 6];
        int[] triangles = new int[width * height * 6];

        for (int y = 0; y < height; y++)
            for (int x = 0; x < width; x++)
                //Debug.Log("x: " + x + ", y: " + y);

                verts[(y * width + x) * 6 + 0] = new Vector3(x, 0, y);
                verts[(y * width + x) * 6 + 1] = new Vector3(x + 1, 0, y);
                verts[(y * width + x) * 6 + 2] = new Vector3(x + 1, .5f, y + 1);

                verts[(y * width + x) * 6 + 3] = new Vector3(x, 0, y);
                verts[(y * width + x) * 6 + 4] = new Vector3(x + 1, .5f, y + 1);
                verts[(y * width + x) * 6 + 5] = new Vector3(x, 0, y + 1);

                uvs[(y * width + x) * 6 + 0] = new Vector2(0, 0);
                uvs[(y * width + x) * 6 + 1] = new Vector2(1, 0);
                uvs[(y * width + x) * 6 + 2] = new Vector2(1, 1);

                uvs[(y * width + x) * 6 + 3] = new Vector2(0, 0);
                uvs[(y * width + x) * 6 + 4] = new Vector2(1, 1);
                uvs[(y * width + x) * 6 + 5] = new Vector2(0, 1);

                for (int t = 0; t < 6; t++)
                    triangles[(y * width + x) * 6 + t] = (y * width + x) * 6 + 5 - t;

        Mesh m = new Mesh();
        m.vertices = verts;
        m.uv = uvs;
        m.triangles = triangles;

        return m;


I can easily render 10 x 10 "chuncks" of 100 x 100 tiles in a scene which is should be enough. However I need the tri's to be able to change material individually, by code. Obviously without (re)generating the mesh again since that does take some time. With the following code I can change and add submeshes to the mesh.

        test.subMeshCount = 2;

        int[] tri1 = new int[] { 5, 4, 3 };
        int[] tri2 = new int[] { 2, 1, 0 };

        test.SetTriangles(tri1, 0);
        test.SetTriangles(tri2, 1);

And it seems like simply adding a Material array to Graphics.DrawMesh(...) but unfortunately it only takes a single material and all the triangles that are out of the submesh group 0 are not being drawn.

I could probably create a GameObject with a renderer component and thrown in the mesh and create my material array there but I don't really need/want a GameObject. I'm just looking for a clean way to render this mesh my script with different materials for it's submeshes by script.

In case you are interested in the stats of rendering 1.000.000 tiles using 100 large meshes here is a screengrab. Looks promising, but I got to be able to change texture/material on individual tiles dynamically. With this setup I might look into a perspective cam and allow for a slightly sharper angle on the camera.

Share this post

Link to post
Share on other sites

Ok, some options:

1) Changing the mesh data:

A texture-atlas ( a single aggregate texture that contains each tile-texture side-by-side ), and each sub-texture can be referenced through enumeration. Using a triangle list, change the tex-coords of a given quad to the appropriate area in a texture-atlas.

2) using a shader:
You have a texture-atlas. You have a second texture, which contains the map-tile-info in each pixel, such as texture-atlas-index. Pixel (0,0) refers to tile(0,0), and contains a texture-atlas index in say channel R. The shader then grabs the texture-atlas index (channel R) and applies that part of the texture-atlas to the quad. 

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

  • Advertisement
  • Advertisement
  • Popular Now

  • Advertisement
  • Similar Content

    • By Affgoo
      still a lot of work to do, but its pretty stable  please let me know what you think <3
      Atlas Sentry is a game of destroy everything. Using your turret, simply swivel and shoot your way to victory, upgrading your weapons to unleash destruction on the variety of spaceships. The bigger your combo’s the more score you get! Earn silver as you play and then purchase new weapons and abilities to better deal with your enemy. Different enemies use different tactics and weapons, work out your own priorities in their destruction order. 

      **2 different game modes 
      **A level select mode with 20 difficult levels including a final boss, can you defeat it? **Arcade mode of endless destruction, how long will you last? 
      **High scores to compete against others, see who can take the top spot. 
    • By Chamferbox
      Chamferbox, a mini game asset store has just opened with some nice game assets, 
      Here you can find a free greek statue asset 

      Also check their dragon, zombie dragon and scorpion monster out:

      They're running the Grand Opening Sale, it's 30% off for all items, but for gamedev member, you can use this coupon code:
      to get 50% off prices What are you waiting for, go to
      and get those models now!

      View full story
    • By Dafu
      FES Retro Game Framework is now available on the Unity Asset Store for your kind consideration!
      FES was born when I set out to start a retro pixel game project. I was looking around for an engine to try next. I tried a number of things, from GameMaker, to Fantasy Consoles, to MonoGame and Godot and then ended up back at Unity. Unity is just unbeatable in it's cross-platform support, and ease of deployment, but it sure as heck gets in the way of proper retro pixel games!
      So I poured over the Unity pipeline and found the lowest levels I could tie into and bring up a new retro game engine inside of Unity, but with a completely different source-code-only, classic game-loop retro blitting and bleeping API. Months of polishing and tweaking later I ended up with FES.
      Some FES features:
      Pixel perfect rendering RGB and Indexed color mode, with palette swapping support Primitive shape rendering, lines, rectangles, ellipses, pixels Multi-layered tilemaps with TMX file support Offscreen rendering Text rendering, with text alignment, overflow settings, and custom pixel font support Clipping Sound and Music APIs Simplified Input handling Wide pixel support (think Atari 2600) Post processing and transition effects, such as scanlines, screen wipes, screen shake, fade, pixelate and more Deploy to all Unity supported platforms I've put in lots of hours into a very detail documentation, you can flip through it here to get an better glimpse at the features and general overview: http://www.pixeltrollgames.com/fes/docs/index.html
      FES is carefully designed and well optimized (see live stress test demo below). Internally it uses batching, it chunks tilemaps, is careful about memory allocations, and tries to be smart about any heavy operations.
      Please have a quick look at the screenshots and live demos below and let me know what you think! I'd love to hear some opinions, feedback and questions!
      I hope I've tickled your retro feels!

      More images at: https://imgur.com/a/LFMAc
      Live demo feature reel: https://simmer.io/@Dafu/fes
      Live blitting stress test: https://simmer.io/@Dafu/fes-drawstress
      Unity Asset Store: https://www.assetstore.unity3d.com/#!/content/102064

      View full story
    • By DevdogUnity

      Ho ho ho
      Tis the season of Christmas surprises, and we have a awesome one for you! 🎅  
      Sponsored by all your favorite Unity Asset Store developers, Nordic Game Jam, Pocket Gamer Connects, and co-hosted by Game Analytics, we (Joris and I – Devdog) are launching the second edition of our yearly Christmas Giveaway Calendar for all Unity game developers!
      You can already now sign up right here.
      So what’s this all about?
      For the past weeks, we’ve been collecting sponsored gifts related to Unity (asset vouchers, product keys, conference tickets etc.), and throughout each day of December leading up to Christmas Day on the 25th, we will be sending out these sponsored gifts as early gamedev Christmas presents via e-mail to hundreds of lucky winners.
      The total prize pool is at $35,000, with over 1200 presents donated by the awesome sponsors!
      Merry Christmas from Devdog, Game Analytics, and every single one of the sponsors.

      View full story
    • By sveta_itseez3D
      itSeez3D, a leading developer of mobile 3d scanning software, announced today a new SDK for its automatic 3D avatar generation technology, Avatar SDK for Unity. The Avatar SDK for Unity is a robust plug-n-play toolset which enables developers and creatives to integrate realistic user-generated 3D avatars into their Unity-based applications. SDK users can allow players to create their own avatars in the application or integrate the SDK into their own production processes for character design and animation.
      “Virtual avatars have recently become increasingly popular, especially in sports games and social VR apps. With the advance of VR and AR, the demand to get humans into the digital world is only increasing”, said Victor Erukhimov, itSeez3D CEO. “Our new Avatar SDK for Unity makes it super-easy to bring the avatar technology into any Unity-based game or VR/AR experience. With the Avatar SDK for Unity now every developer can bring face scanning technology into their games and allow players to create their own personalized in-game avatars, making the gameplay much more exciting and immersive.”
      Key features of the Avatar SDK for Unity:
      Automatic generation of a color 3D face model from a single selfie photo in 5-10 seconds (!). Works best with selfies, but can be used with any portrait photo.
      Shape and texture of the head model are unique for each person, synthesized with a deep learning algorithm crafted by computer vision experts
      Head models support runtime blendshape facial animations (45 different expressions)
      Generated 3D heads include eyes, mouth, and teeth
      Algorithms synthesize 3D meshes in mid-poly resolution, ~12k vertices, and ~24k triangles
      Six predefined hairstyles with hair-recoloring feature (many more available on request)
      Avatar generation API can be used in design-time and in run-time, which means you can allow users to create their own avatars in your game
      Cloud version is cross-platform, and offline version currently works on PCs with 64-bit Windows (support for more platforms is coming soon)
      Well-documented samples showcasing the functionality.
      The Avatar SDK for Unity is offered in two modes - “Cloud” and “Offline”. The “Cloud” version is available at http://avatarsdk.com/ and the “Offline” version is available by request at support@itseez3d.com.
      About itSeez3D
      At itSeez3D, we are working on the computer vision technology that turns mobile devices into powerful 3D scanners. itSeez3D has developed the world's first mobile 3D scanning application that allows to create high-resolution photorealistic 3D models of people's' faces, bodies and objects. The application is available for iOS and Windows OS mobile devices powered with 3D cameras. In 2016 the company introduced Avatar SDK that creates a realistic 3D model of a face from a single selfie photo. To learn more about itSeez3D scanning software and 3D avatar creation technology, please visit www.itseez3d.com and www.avatarsdk.com.

      View full story
  • Advertisement