Template for #unity3d to test custom procedural game meshes

One of Unity’s dirty secrets is that (out of the box) it’s plain awful as a prototyping tool. You can fix that, but it requires quite a lot of work. I’m going to start publishing my fixes one by one. Here’s the first: a test-bed for making custom meshes.

A very common thing you need to during Unity gamedev – creating and testing algorithms for generating and manipulating meshes – is a pain. There’s custom classes and editors and stuff you have to write before you can create a single, basic, mesh.

One of Unity’s silly failings is that they don’t allow custom “new-project” templates, as if we were stuck in 1980 and hadn’t learned how to make IDE’s yet.

I’ve created a minimal example (should work with all versions of Unity 3.x through 5.x) which automatically creates a single mesh and scales it to fit your camera, and centers it on that camera’s screen, but positioned on Z=0, so that it doesn’t get clipped.

This solves 4 or 5 of the most common “dumb mistakes” I tend to make when trying to add new Mesh-generation code from scratch to an existing Unity project. Gives me a good starting point for new projects

Usage

The tri has center of base at the local origin of the camera, and the tip of the triangle precisely touching the top edge of the screen. This should make it very easy to visually check your meshes are generating at right position/orientation/location.

I’m assuming you’ll build your meshes in 2D; nearly all gamedev algorithms work in 2D first and are extrapolated to 3D, so that’s how I recommend writing and testing them. Once it works in 2D, move your code to a “real” game project and start doing the 3D version. This project is simply to get you up and running quickly when prototyping new Mesh-gen ideas.

I’m also assuming you’ll deal with material + texture + lighting yourself – many algorithms don’t even use textures, either because they’re using shaders (in which case you’d want to test UV too, but I’ve left that out here), or because they’re raw topology algorithms that don’t care about rendering.

So … you’ll get a pink triangle to start with. If you’re making custom mesh algorithms, you most certainly should already know how to create and attach materials in code!

Bonus: won’t delete data

There’s some code in there that each time you re-gen, it automatically gives a new name to next item, and doesn’t delete the old. You might want to remove that and have it automatically delete the old test data each time. But I erred on the side of caution.

Installation

  1. Create an empty Unity project. This will have a camera by default (required!)
  2. Select the camera and set it to “Orthogonal”
  3. Create a new folder “Editor” (required by Unity Corp to workaround absurd bugs in Unity’s build system)
  4. Create a file in that called “TestTriGen1.cs”
  5. Copy/Paste the source into that file
  6. Save the file, go back to Unity.
  7. Wait a few seconds
  8. A menu will appear “TriGen”, click the one item in that menu
  9. Click your camera to see the Unity preview: you should see a large pink triangle

Code

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

using UnityEditor;

public class TestTriGen1 : MonoBehaviour
{

private static TestTriGen1 _ttg;
[MenuItem("TriGen/TriGen")]
public static void GenTris()
{
if( _ttg == null)
_ttg = new TestTriGen1();

_ttg.gen();
}

public void gen()
{
Camera camera = Camera.main;
float MeshDiameter = camera.orthographicSize;

		string _parentName = "Gen'd tris";
GameObject parent = GameObject.Find( _parentName );
 if( parent == null ) parent = new GameObject( _parentName );

int numChildren = parent.transform.childCount;
GameObject area = new GameObject("Area "+(1+numChildren));
area.transform.parent = parent.transform;
		area.transform.position = new Vector3( camera.transform.position.x, camera.transform.position.y, 0 );

MeshRenderer mr = area.AddComponent<MeshRenderer>();
MeshFilter mf = area.AddComponent<MeshFilter>();
Mesh m = new Mesh();
mf.mesh = m;

Vector3[] vs = new Vector3[3];
vs[0] = new Vector3(0,1f * MeshDiameter,0);
		vs[1] = new Vector3(0.5f * MeshDiameter,0,0);
		vs[2] = new Vector3(-0.5f * MeshDiameter,0f,0);
		
		int[] tris = new int[3];
		tris[0] = 0;
		tris[1] = 1;
		tris[2] = 2;
		
		m.vertices = vs;
		m.triangles = tris;
}
}

6 thoughts on “Template for #unity3d to test custom procedural game meshes

  1. Dan

    Ii was under the impression that Unity was a good prototyping tool. If not, what, in your opinion, are some good prototyping tools? Preferrably ones that work well with Unity?

  2. Adam

    For 2d work, flash is still good, and the craopy make-a-game apps are good for some things.

    For 3d work, I’ve not been impressed by anything, although unreals blueprints look good – I haven’t done anything exciting with them yet though

  3. Sampsa

    “[Unity] it’s plain awful as a prototyping tool” I’m sorry but you’re making it really hard to take you seriously.

    While Unity certainly has its flaws, I’ve never seen anything like it regarding the speed of iteration and prototyping. Flash is nice, but it has nothing that I couldn’t do with Unity, and I most certainly can’t do a FPS game (or proto) in Flash. I haven’t looked into UE4, but we did use UE3. And I can tell you that making or prototyping anything else than a FPS with UE3 felt wrong in so many ways.

    In fact, I think Unity is too easy for prototyping. Thanks to Unity, there is currently a shit load of crap in Steam/Greenlight. Ready-made assets stitched together with almost no programming experience, or blatant asset flips from AssetStore. Not that it’s Unity’s fault. I blame Valve for letting crap get through.

    Anyway, that’s not why I’m writing this. While your procedural mesh stuff example has a good intention in it, I has few flaws.
    1) TestTriGen1 is derived from a MonoBehaviour, but not used as one. Instead it’s used as an editor extension. You could do all that without deriving from MonoBehaviour and using static functions…
    2) …which brings us to the second issue. Your generator is not data-driven, and cannot be made such easily. Why not create the generator as a MonoBehavour, and then have a Rebuild() method that generates the mesh when needed, using the parameters in the component (radius, tesselation etc params)
    3) Your generator depends on camera (and assumes it being orthographic). Together with points 1 and 2 this makes it quite bizarre combination IMO.

    Have you seen other procedural mesh generation tutorials for Unity? There’s a lot of good stuff.

    http://kobolds-keep.net/?p=33
    http://forum.unity3d.com/threads/catlike-codings-c-tutorials.98761/

  4. adam Post author

    I like your mention of the “shit load of crap in Steam/Greenlight”. It’s impressively bad … but I think it shows Unity is great for “taking things you already have, that were explicitly made to work together, and make them work together” but very bad for “modifying, improving, changing, re-designing, re-creating, exploring new ideas”.

    A great prototyping tool is NOT about copy/pasting things together – that’s a terrible tool, it will encourage you to stop prototyping and simply re-clone what you already did. This is one place where Unity falls down, IMHO and IME.

    In particular, Unity’s tech leadership has chosen to FUBAR the C# language rather than fix their core bugs. C# is a modern langauge with great features to support and promote code re-use and sharing; Unity craps on most of them. Some of it is stunning – “let’s use Reflection to break C# constructors, and fundamentally destroy the runtime by making it do things its explicitly not allowed to do! YEAH!” (I didn’t even think that was possible until I saw it in Unity. It’s great that C# is so flexible you can FUBAR the language at runtime, but … wow. Not a good path to go down)

  5. adam Post author

    Re: tutorials – this is ABSOLUTELY NOT a tutorial. If you’ve done crap loads of work with meshes (probably for years before you’d heard of Unity) this is a useful template. If you’re looking to learn how to do meshes in Unity, please do NOT use this post.

    As per the post, this is a new-project template that you need frequently when testing out procedural generation ideas. Yes, it requires ortohographc camera … becuase you MUST use an ortho camera when prototyping many/most 3D algos: you always start off with the 2D version, as it reduces development time by a large factor, and move on to 3D only when your algo provably works. On top of that, many algos are 2D anyway, even when run in 3D. Of the rest, even once they work, many are still best to do the 3D tests initially in a 2D view while operating on 3D data, and check that when you added a 3D dimension none of your 2D code broke (e.g. calculaions of vector magnitude is a common one to go wrong. I have seen that multiple times over the years).

    Things like CatLikeCoding are great for what they are, but they’re masses of work and very time-consuming when what you need is something you can start typing a mesh-deformation test in under 30 seconds … not spend 15 minutes reading through a tutorial (that tells you literally nothing; you already knew all of it) trying to pull out small bits of code you can copy/paste into place.

    YMMV…

  6. adam Post author

    FYI: 1) is derived from MB because Unity’s crappy “new file” template (which you cannot access any more – it used to be accessible as a file, but they blocked that in Unity 5, at least on Mac) always makes an MB whether you want it or not.

    (incidentally: that’s another black mark against Unity for prototyping IMHO)

    Anyway … so what? It costs nothing, it’s not even a distraction :).

    2) if you need that, it’s trivial to write on top after creating the project. Most of the time when I’m testing algos, I don’t need or want a data-driven approach – I’ll add that in a game-specific manner when I move the code over into a live project. YMMV

Leave a Reply

Your email address will not be published. Required fields are marked *