- Home /
Auto-snap script?
I have some Gameobjects in my scene that needs to be snapped to the grid, i can hold Ctrl while moving them to snap them but is there a way to write a script for these Gameobjects that will auto-snap them when moved?
Thanks!
Try to attach this simple script to your GameObjects.
using UnityEngine;
[ExecuteInEdit$$anonymous$$ode]
public class Autosnap : $$anonymous$$onoBehaviour {
void Update ()
{
transform.position = new Vector3($$anonymous$$athf.Round(transform.position.x), transform.position.y, $$anonymous$$athf.Round(transform.position.z));
}
}
That seems to work however what if i wanted to snap to a particular value like 0.16 or 0.32 ?
Answer by Khena_B · Dec 29, 2016 at 02:23 PM
Well here's what i came up with, i'm pretty new to coding so there might be a simpler solution, but it works
using UnityEngine;
[ExecuteInEditMode]
public class AutoSnap : MonoBehaviour
{
public float snapValueX;
public float snapValueY;
public float snapValueZ;
void Update ()
{
if (snapValueX != 0)
transform.position = new Vector3(Mathf.Round(transform.position.x * (1 / snapValueX)) / (1 / snapValueX),transform.position.y, transform.position.z);
if (snapValueY != 0)
transform.position = new Vector3(transform.position.x, Mathf.Round(transform.position.y * (1 / snapValueY)) / (1 / snapValueY), transform.position.z);
if(snapValueZ != 0)
transform.position = new Vector3(transform.position.x, transform.position.y, Mathf.Round(transform.position.z * (1 / snapValueZ)) / (1 / snapValueZ));
}
}
I didn't want the objects to snap at runtime so i've added a condition
if (!Application.isPlaying)
Your answer
Follow this Question
Related Questions
Deleted object tagged as missing instead of null. 0 Answers
Raycast instantiating object to grid 0 Answers
Snap to grid after click and drag? 2 Answers
Snap to grid not working for me 1 Answer