I’m still not very good with coding, but I wanted to try to make a bit more versatile in case i wanted to change the size of the cube. I thought I’d share what I came up with in case someone else wanted to do something similar.
It basically find the scale size of the cube and adjusts the grid size to the cube. You can scale each axis of the cube individually and it will still work.
Cubes of different sizes don’t really connect well together since they’re on individual grids, but here’s an example of what the code does.
I’ve also added a boolean on whether or not it should be grid or cube based, so it can be switched back and forth from what Ben does in his tutorial.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;[ExecuteInEditMode]
public class EditorSnap : MonoBehaviour
{
[SerializeField] bool isFixedGrid = true;
[SerializeField] [Range(1f,20f)] float gridSize = 10f;private Vector3 snapPos; void Update () { //find the size of the cubes scale if (isFixedGrid == false) { Vector3 cubeSize; //get the scale of each side of the cube cubeSize.x = transform.localScale.x; //cubeSize.y = transform.localScale.y; cubeSize.z = transform.localScale.z; snapPos.x = Mathf.RoundToInt(transform.position.x / cubeSize.x) * cubeSize.x; //snapPos.y = Mathf.RoundToInt(transform.position.y / cubeSize.y) * cubeSize.y; snapPos.z = Mathf.RoundToInt(transform.position.z / cubeSize.z) * cubeSize.z; transform.position = new Vector3(snapPos.x, 0f, snapPos.z); } else //grid is independent of the cube size. { snapPos.x = Mathf.RoundToInt(transform.position.x / gridSize) * gridSize; snapPos.z = Mathf.RoundToInt(transform.position.z / gridSize) * gridSize; //snap the cube to the grid. transform.position = new Vector3(snapPos.x, 0f, snapPos.z); } }
}