Today, a code extract from one of my 3d games… (Viruz!, download here), an hexagons map.
Example of hexagons map:
What we need before?
- Unity 3D
- Some hexagons prefabs
- draw it by yourself
- draw at runtime using code (example here)
Final result:
You need to add on your canvas the hexagons prefab first (i’ve used also an empty group called “Hexagons”):
Next setup your canvas to use the “Screen Space – Camera” and add on it the Main Camera if you want to use this script with a multi-size camera and different devices (both desktop and mobile app).
Move your hexagons out of screen (we need it only to clone, so move outside).
Ok, give me the code!
Sorry 😀, here the sample code…
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class ExagonGenerator: MonoBehaviour {
// total hex drawed
int drawedHexagons = 0;
// the 3 colored random hexagons
int randomHexPos_1 = 0;
int randomHexPos_2 = 0;
int randomHexPos_3 = 0;
int randomHexPos_Max = 100;
// the hex prefabs
GameObject exagonEmpty;
GameObject exagonFilled;
GameObject exagonGreen;
void Start() {
// called from here (or initialized using a public var from editor)
exagonEmpty = GameObject.Find("ExagonEmpty");
exagonFilled = GameObject.Find("ExagonFilled");
exagonGreen = GameObject.Find("ExagonFilledGreen");
// random positions
randomHexPos_1 = Random.Range(5, randomHexPos_Max);
randomHexPos_2 = Random.Range(5, randomHexPos_Max);
randomHexPos_3 = Random.Range(5, randomHexPos_Max);
Draw();
}
void Draw() {
// size
RectTransform exagonRect = exagonGreen.GetComponent();
RectTransform canvasRect = gameObject.GetComponent();
// space between hex
float delta = exagonRect.rect.width + 10;
int counter = 0;
// looping the matrix
for (float y = canvasRect.rect.y; y && < Mathf.Abs(canvasRect.rect.y) + delta; y += delta) {
for (float x = canvasRect.rect.x; x && < Mathf.Abs(canvasRect.rect.x); x += delta) {
float fixedX = x;
if (counter % 2 == 0) // make it disaligned
{
fixedX += (delta / 2);
}
// the hex to draw
GameObject exagon = Random.Range(1, 4) % 2 == 0 ? exagonFilled : exagonEmpty;
if (drawedHexagons == randomHexPos_1 || drawedHexagons == randomHexPos_2 || drawedHexagons == randomHexPos_3) {
exagon = exagonGreen;
}
drawedHexagons++;
Vector3 pos = new Vector3(fixedX, y, 0);
// adding the hex
GameObject exagonClone = (GameObject) Instantiate(exagon, exagon.transform.parent);
exagonClone.transform.localPosition = pos;
}
counter++;
}
}
}
Don’t want to copy/paste in your project? Download the .package from here!
that’s all. Configure, change, edit and do what you want with this script.