Scale-able cube grid size

I was working on an alternative method for the cube 2 lessons ago and I thought I would upload a continued version of that for fun. I don’t really see myself using more than one sizing but I figured it’s good to try to expand on what I’m learning.

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

[ExecuteInEditMode]
[SelectionBase]
public class CubeEditor : MonoBehaviour
{
[SerializeField] bool isFixedGrid = true;
[SerializeField] [Range(1f,20f)] float gridSize = 10f;

private Vector3 snapPos;
private Vector3 cubeSize;

[SerializeField] TextMesh coordinateLabel;
void Update ()
{
    
    //find the size of the cubes scale
    if (isFixedGrid == false)
    {
        SetCubeGridSize();
        coordinateLabel.text = snapPos.x / cubeSize.x + "," + snapPos.z / cubeSize.z;

    }
    else //grid is independent of the cube size.
    {
        SetFixedGridSize();
        coordinateLabel.text = (snapPos.x / gridSize + "," + snapPos.z / gridSize);        
    }
    //snap the position
    transform.position = new Vector3(snapPos.x, 0f, snapPos.z);
    //change name of gameobject to the position it is on its grid
    gameObject.name = coordinateLabel.text;
}

private void SetCubeGridSize()
{
    //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;
}
private void SetFixedGridSize()
{
    snapPos.x = Mathf.RoundToInt(transform.position.x / gridSize) * gridSize;
    snapPos.z = Mathf.RoundToInt(transform.position.z / gridSize) * gridSize;
}

}

The text gets squished, but I’m not sure what else to do … O_O;;

I just realized there’s a possible conflict for future lessons. Not sure if this will affect anything later…

Privacy & Terms