【Unity】移动父对象位置小工具、移动物品中心点位置

这篇博客介绍了一个Unity编辑器扩展脚本,通过Shift+M快捷键实现选中物体的中心点移动,而不会影响其子物体的位置。脚本使用Handles组件进行交互,方便开发者在场景视图中快速调整物体位置。
  • 平时有时候只想移动物体的中心点,但是每次快捷编辑起来有点麻烦,所以写了个小脚本
  • 选中物体后按 shift + m 就可以移动物体,而不影响子问题的位置了
using UnityEditor;
using UnityEngine;

[InitializeOnLoad]
public class MoveRootPointEditor
{
    public static bool openMove = false;
    [InitializeOnLoadMethod]
    public static void OnInit()
    {
        SceneView.duringSceneGui+=SceneViewOnduringSceneGui;
        Selection.selectionChanged+=SelectionChanged;
    }

    private static void SelectionChanged()
    {
        openMove = false;
    }

    [MenuItem("Assets/SceneEditorTool/MoveRootPoint #M")]
    public static void OpenCheck()
    {
        openMove = true;
    }

    private static void SceneViewOnduringSceneGui(SceneView obj)
    {
        if (!openMove)
        {
            return;
        }
        if (Selection.activeGameObject==null)
        {
            return;
        }
        Transform component = Selection.activeGameObject.GetComponent<Transform>();
        if (component==null)
        {
            return;
        }
        Vector3 delta = Vector3.one*obj.size*0.1f;
        Vector3 checkPoint = component.position-delta;
        
        Handles.DrawWireCube(checkPoint,delta);
        
        Vector3 newPoint= Handles.PositionHandle(checkPoint, Quaternion.identity);

        if (newPoint!=checkPoint)
        {
            Undo.RecordObject(component,"MoveRootPoint");
            
            component.position = newPoint + delta;
            int componentChildCount = component.childCount;
          
            EditorUtility.SetDirty(component);
            
            for (int i = 0; i < componentChildCount; i++)
            {
                Transform transform = component.GetChild(i).transform;
                
                Undo.RecordObject(transform,"MoveRootPoint");

                transform.position-=newPoint-checkPoint;
                
                EditorUtility.SetDirty(transform);
            }
        }
    }

}
```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值