Nerd For Tech
Published in

Nerd For Tech

A Custom Flower Generator Using Dynamic Meshes In Unity

Recently I had some free time and had the idea to make this. It’s my first time dynamically creating a mesh in code.

My custom flower generator with 2 petal layers

Design and Inspiration:

I have no idea what made me think of making this, but I just had the idea all of a sudden.

After watching a few YT videos by Brackeys and Code Monkey, I had a general idea how to create the meshes.

From there I just trial-and-error-ed my way to create the petal, then dynamically duplicated it in 360 degrees using some bullet hell code from a recent project.

After that, just duplicate everything for the 2nd layer of petals.

The generator uses 3 Animation Curves from Unity to control the width, height, and depth/length of each petal. The width and height of each vertices in the petal is calculated based on how far, from start to end, along the depth the vertices is.

The code:

Note: This is my first time making custom meshes with code, so there’s probably many ways to improve this code.

CreateShape():

Each petal has 17 vertices, specified by the “_detail” int variable, which equals the number of vertices along the length minus 1.

Don’t ask why I did it that way. ¯\_( ͡• ͜ʖ ͡•)_/¯

Point being, that I can change the detail level with relative ease.
This dynamically creates and positions the vertices in the petal. The first point then all the mid-points, then the end point.
I couldn’t think of a way to automate the creation of the triangles used to render the shape, so I just wrote them out by hand.

UpdateMesh():

This clears and updates the mesh each frame, to allow for runtime modification.

Start():

Initialize the two layers of petals, duplicating and rotating each based on the number to spawn per layer.

Update():

Every frame, recreate the mesh and update the mesh renderer.

The result is a pretty good looking procedural flower generator; Easily customized to almost any requirements.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Vincent Taylor

Vincent Taylor

Unity game developer / C# Programmer / Gamer. Australian (Tasmanian) indie games developer for 10+ years. Currently looking for games industry employment.