×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: C#
Posted by: Charles McCann
Added: Aug 21, 2016 1:21 PM
Views: 9
Unity3d: Use Menu to align selected object to ground (collider under it).
  1. using UnityEngine;
  2. using UnityEditor;
  3. using System.Collections
  4.  
  5. public class AlignWithGround : MonoBehaviour {
  6.     [MenuItem ("Tools/Transform Tools/Align with ground %t")]
  7.     static void AlignWithGround () {
  8.         Transform [] transforms = Selection.transforms;
  9.         foreach (Transform myTransform in transforms) {
  10.             RaycastHit hit;
  11.             if (Physics.Raycast (myTransform.position, -Vector3.up, out hit)) {
  12.                 Vector3 targetPosition = hit.point;
  13.                 if (myTransform.gameObject.GetComponent<MeshFilter>() != null) {
  14.                     Bounds bounds = myTransform.gameObject.GetComponent<MeshFilter>().sharedMesh.bounds;
  15.                     targetPosition.y += bounds.extents.y;
  16.                 }
  17.                 myTransform.position = targetPosition;
  18.                 Vector3 targetRotation = new Vector3 (hit.normal.x, myTransform.eulerAngles.y, hit.normal.z);
  19.                 myTransform.eulerAngles = targetRotation;
  20.             }
  21.         }
  22.     }
  23. }