SnapToGrid

From Unify Community Wiki
(Difference between revisions)
Jump to: navigation, search
m (Text replace - "</csharp>" to "</syntaxhighlight>")
m (Text replace - "<javascript>" to "<syntaxhighlight lang="javascript">")
Line 43: Line 43:
  
 
== Javascript - SnapToGrid.js ==
 
== Javascript - SnapToGrid.js ==
<javascript>@MenuItem ("GameObject/Snap to Grid %g")
+
<syntaxhighlight lang="javascript">@MenuItem ("GameObject/Snap to Grid %g")
 
static function MenuSnapToGrid()
 
static function MenuSnapToGrid()
 
{
 
{

Revision as of 20:48, 10 January 2012

Author: Hayden Peake (Hayden)

Contents

Description

Snaps objects to a grid in 3 dimensions. The grid spacing may be different for each axis.

Usage

You must place the script in a folder named Editor in your project's Assets folder for it to work properly.

Select some objects in the Scene view or Hierarchy window, then choose GameObject→Snap to Grid from the menu (or press control G). Each selected object will be independently snapped to a unit grid.

If you require a different grid spacing, change gridx, gridy, and gridz below.

C# - SnapToGrid.cs

using UnityEngine;
using UnityEditor;
using System.Collections;
 
public class SnapToGrid : ScriptableObject
{
    [MenuItem ("GameObject/Snap to Grid %g")]
    static void MenuSnapToGrid()
    {
        Transform[] transforms = Selection.GetTransforms(SelectionMode.TopLevel | SelectionMode.OnlyUserModifiable);
 
        float gridx = 1.0f;
        float gridy = 1.0f;
        float gridz = 1.0f;
 
        foreach (Transform transform in transforms)
        {
            Vector3 newPosition = transform.position;
            newPosition.x = Mathf.Round(newPosition.x / gridx) * gridx;
            newPosition.y = Mathf.Round(newPosition.y / gridy) * gridy;
            newPosition.z = Mathf.Round(newPosition.z / gridz) * gridz;
            transform.position = newPosition;
        }
    }
}

Javascript - SnapToGrid.js

@MenuItem ("GameObject/Snap to Grid %g")
static function MenuSnapToGrid()
{
    var transforms : Transform[] = Selection.GetTransforms(SelectionMode.TopLevel | SelectionMode.OnlyUserModifiable);
 
    var gridx : float = 1.0;
    var gridy : float = 1.0;
    var gridz : float = 1.0;
 
    for (var transform : Transform in transforms)
    {
        var newPosition : Vector3 = transform.position;
        newPosition.x = Mathf.Round(newPosition.x / gridx) * gridx;
        newPosition.y = Mathf.Round(newPosition.y / gridy) * gridy;
        newPosition.z = Mathf.Round(newPosition.z / gridz) * gridz;
        transform.position = newPosition;
    }
}</javascript>
 
 
[[Category:Editor Scripts]]
[[Category:ScriptableObject]]
[[Category:C Sharp]]
[[Category: JavaScript]]
Personal tools
Namespaces

Variants
Actions
Navigation
Extras
Toolbox