Last active
March 12, 2025 17:19
-
-
Save s4lt3d/57d6d6740f092ce36de0a9d4622727c5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using UnityEngine; | |
| [RequireComponent(typeof(Collider))] | |
| public class SnapToGround2 : MonoBehaviour | |
| { | |
| public GameObject objectToSpawn; | |
| public float timeToSpawn = 0.1f; | |
| void SnapRotatedObjectToGround() | |
| { | |
| GameObject objectToMove = gameObject; | |
| Collider collider = objectToMove.GetComponent<Collider>(); | |
| Vector3 lowestPoint = collider.bounds.min; | |
| RaycastHit hit; | |
| if (Physics.Raycast(lowestPoint + Vector3.up * 0.1f, Vector3.down, out hit)) | |
| { | |
| float distanceToMoveDown = Vector3.Distance(lowestPoint, hit.point); | |
| objectToMove.transform.position -= Vector3.up * distanceToMoveDown; | |
| } | |
| if (objectToSpawn != null) | |
| Invoke("SpawnObject", timeToSpawn); | |
| } | |
| void SpawnObject() => Instantiate(objectToSpawn, transform.position + Vector3.forward * 1.5f + Vector3.up * 2, | |
| Random.rotation); | |
| void Start() | |
| { | |
| Invoke("SnapRotatedObjectToGround", timeToSpawn); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using UnityEditor; | |
| using UnityEngine; | |
| public class SnapToGroundEditor : Editor | |
| { | |
| private const string UNDO_GROUP_NAME = "Snap to Ground"; | |
| [MenuItem("GameObject Tools/Snap to Ground %g")] | |
| static void SnapToGround() | |
| { | |
| Undo.SetCurrentGroupName(UNDO_GROUP_NAME); | |
| foreach (GameObject gameObject in Selection.gameObjects) | |
| { | |
| Collider collider = gameObject.GetComponent<Collider>(); | |
| if (!collider) | |
| { | |
| Debug.LogWarning("GameObject " + gameObject.name + " does not have a collider.", gameObject); | |
| continue; | |
| } | |
| Vector3 lowestPoint = collider.bounds.min; | |
| RaycastHit hit; | |
| if (Physics.Raycast(lowestPoint + Vector3.up * 0.1f, Vector3.down, out hit)) | |
| { | |
| Undo.RecordObject(gameObject.transform, UNDO_GROUP_NAME); | |
| float distanceToMoveDown = Vector3.Distance(lowestPoint, hit.point); | |
| gameObject.transform.position -= Vector3.up * distanceToMoveDown; | |
| Undo.CollapseUndoOperations(Undo.GetCurrentGroup()); | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment