Unity3D – Snap object in editor grid

Welcome back,

I want to share a way to draw in Unity3d editor a cubes based grid that allow you to snap objects in the same position and make a cube grid, like this:

First of all, create a new Cube object using Quads: compose all the 6 faces and save it as a prefab.

Align all the faces and save as Prefab.


Now on the “Top” face of your cube, add an empty Object and attach a Text Renderer and a Text Mesh, for adding a new label:

Center it on your cube, adjust font and size and you should see something like this:

0.0 are respectively the X and the Y position of your cube.


Let’s code!

Add a new C# script and assign on your prefab. Call it “EditorSnap.cs” and open it.

We introduce “[ExecuteInEditMode]” a behaviour that makes all instances of a script execute in Edit Mode.

https://docs.unity3d.com/ScriptReference/ExecuteInEditMode.html


Copy the example code and try it. If it works let’s go to edit our script:

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

// Makes all instances of a script execute in Edit Mode
[ExecuteInEditMode]
[SelectionBase]

public class EditorSnap : MonoBehaviour
{
    // Add an editor field, "SerializeField" with a custom range slider, from 1 to 20. Default value is 10.
    [SerializeField] [Range(1f, 20f)] float gridSize = 10f;

    // Attach your label
    TextMesh textMesh;

    void Update()
    {
        Vector3 snapPosition;
        // When position of your object change, apply a new position on the x and y axed, based on your grid size.
        snapPosition.x = Mathf.RoundToInt(transform.position.x / gridSize) * gridSize;
        snapPosition.z = Mathf.RoundToInt(transform.position.z / gridSize) * gridSize;

        // Put as text of your label the coordinates
        textMesh = GetComponentInChildren<TextMesh>();
        textMesh.text = snapPosition.x / gridSize + "." + snapPosition.z / gridSize;
        
        // Apply transformation
        transform.position = new Vector3(snapPosition.x, 0f, snapPosition.z);
    }
}

Now your script is ready.

If you duplicate your prefab and try to move, you move following the 10 size step. Try it.

In this simple way you’re able to create grid easily via editor, following sizes and easily snapped to the position you need.


Hint

If your prefab is a little smaller that the grid size, you are able to add a space between blocks, like this:

Or if you prefer, use the same size to create an uniformed grid:


Hint^2

If you need to rename all of your cubes, add this piece of code in your script:

unity3d rename objects from code
Objects take the name of their position axes.
string posText = snapPosition.x / gridSize + "." + snapPosition.z / gridSize;
textMesh.text = posText;

// Rename objects in editor
gameObject.name = posText;

Enjoy and share your result!

 

Alberto Pasca

Software engineer @ Pirelli & C. S.p.A. with a strong passion for mobile  development, security, and connected things.