在Unity拷贝一个游戏物体,得到的游戏物体世界坐标位置和原来的是一样的。如何拷贝一个游戏物体并拷贝其本地坐标位置呢? 思路:克隆选中的游戏物体,并将Transform的本地位置、欧拉角、缩放值赋给克隆后游戏物体。
实现代码:
using UnityEditor;
using UnityEngine;
using System.Collections.Generic;
using System;
public class LocalObjCopy : MonoBehaviour
{
private static Transform[] transforms;
[MenuItem("Component/拷贝选中游戏物体 #c")]
public static void CopyObjs()
{
if (Selection.transforms.Length == 0)
return;
transforms = Selection.transforms;
List<Transform> transList = new List<Transform>(transforms);
transList.Sort(new Comparison<Transform>((Transform a, Transform b) =>
{
return a.GetSiblingIndex() > b.GetSiblingIndex() ? 1 : -1;
}));
transforms = transList.ToArray();
}
[MenuItem("Component/粘贴游戏物体到选中对象下 #v")]
public static void PauseObjs()
{
if (transforms.Length == 0)
return;
foreach (var item in transforms)
{
CopyToActiveObj(item);
}
}
private static void CopyToActiveObj(Transform objTrans)
{
Transform targetTrans = Selection.activeTransform;
Transform cloneObjTrans = Instantiate(objTrans.gameObject, targetTrans).transform;
cloneObjTrans.gameObject.name = objTrans.gameObject.name;
CopyTransValue(objTrans, cloneObjTrans);
}
private static void CopyTransValue(Transform trans, Transform toTrans)
{
toTrans.localPosition = trans.localPosition;
toTrans.localEulerAngles = trans.localEulerAngles;
toTrans.localScale = trans.localScale;
}
}
按快捷键Shift+C、Shift+V拷贝粘贴,粘贴是粘贴到当前选中物体的下方,可多选拷贝。
|