背景
モック制作で標準の立体を組み合わせたり拡縮・回転したりする機会がありました。
その過程で、子の配置を維持したまま親の Transform をリセットしたくなりました。
しかし、親の Transform をいじると子や孫の配置が変動してしまいます。
そこで、子の配置を維持したまま親の Transform をリセットする拡張を作りました。
備考
回転と拡縮が絡んだ状態でリセットすると歪んだ見た目になる恐れがあります。
より凝ったモックの地形を作る際は ProBuilder (無料)がおすすめです。
コード
下記をプロジェクトに追加して GameObject を右クリックすると、メニューにReset Transform
が追加されます。
ResetTransformEditor.cs
#if UNITY_EDITOR
using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
public class ResetTransformEditor
{
[MenuItem("GameObject/Reset Transform/All", false, 1000)]
public static void ResetTransform()
{
foreach (var go in Selection.gameObjects)
{
ResetProcess(go.transform, t =>
{t.
t.SetLocalPositionAndRotation(Vector3.zero, Quaternion.identity);
t.localScale = Vector3.one;
});
}
}
[MenuItem("GameObject/Reset Transform/Position", false, 1000)]
public static void ResetPosition()
{
foreach (var go in Selection.gameObjects)
{
ResetProcess(go.transform, t => t.localPosition = Vector3.zero);
}
}
[MenuItem("GameObject/Reset Transform/Rotation", false, 1000)]
public static void ResetRotation()
{
foreach (var go in Selection.gameObjects)
{
ResetProcess(go.transform, t => t.localRotation = Quaternion.identity);
}
}
[MenuItem("GameObject/Reset Transform/Scale", false, 1000)]
public static void ResetScale()
{
foreach (var go in Selection.gameObjects)
{
ResetProcess(go.transform, t => t.localScale = Vector3.one);
}
}
private static void ResetProcess(Transform parent, Action<Transform> action)
{
var poses = new List<Vector3>();
var rots = new List<Quaternion>();
var scales = new List<Vector3>();
for (int i = 0; i < parent.childCount; i++)
{
var t = parent.GetChild(i);
poses.Add(t.position);
rots.Add(t.rotation);
scales.Add(new Vector3(
t.localScale.x * parent.localScale.x,
t.localScale.y * parent.localScale.y,
t.localScale.z * parent.localScale.z));
}
action.Invoke(parent);
for (int i = 0; i < parent.childCount; i++)
{
var t = parent.GetChild(i);
t.SetPositionAndRotation(poses[i], rots[i]);
t.localScale = scales[i];
}
}
}
#endif