Skip to content

Instantly share code, notes, and snippets.

@beardordie
Created July 3, 2019 01:59
Show Gist options
  • Save beardordie/b031252c642a4c187b3bd47bde35a69a to your computer and use it in GitHub Desktop.
Save beardordie/b031252c642a4c187b3bd47bde35a69a to your computer and use it in GitHub Desktop.
Unity Editor script with shorcut key (Shift + End) to snap a selected object to the surface beneath it, with full undo support
using UnityEditor;
using UnityEngine;
public class SnapToGround : Editor
{
[MenuItem("Tools/Snap Selection To Ground #END")]
public static void SnapToGroundNow()
{
foreach (Transform t in Selection.transforms)
{
Undo.RegisterCompleteObjectUndo(Selection.transforms, "SnapToGroundNow");
MeshRenderer renderer = t.GetComponentInChildren<MeshRenderer>();
if (renderer != null)
{
RaycastHit rayhit;
if (Physics.Raycast(renderer.bounds.center, Vector3.down, out rayhit))
{
float offsetY = rayhit.point.y - renderer.bounds.min.y;
t.position += new Vector3(0f, offsetY, 0f);
}
}
}
}
}
@beardordie
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment