Unity中恢复Prefab关联或批量替换对象

丢失关联丢失Prefab,会造成一些小麻烦,有时候也需要批量的将一些对象换成同一个对象,或者恢复丢失的关联Prefab,可以试着用下面这个脚本.

如果只是删除预设,建议使用Break Prefab Instance 取消Prefab的关联,再删除Prefab源,否则场景中物体名会变红.



下面这个脚本是批量替换或恢复Prefab关联,放在Editor目录下,然后选择场景中要被替换的对象,再在GameObject菜单下找到Replae Selection.设置Replacement Object后,执行,即可将所选择的所有对象替换为Replacement Object里设置的对象,但是原有的层级关系,位置,旋转,缩放值将会保持不变.

脚本 ReplaceSelection.cs

/* This wizard will replace a selection with an object or prefab.
* Scene objects will be cloned (destroying their prefab links).
* original coding by 'yesfish', nabbed from Unity Forums
* 'keep parent' added by Dave A (also removed 'rotation' option, using localRotation
*/
using UnityEngine;
using UnityEditor;
using System.Collections;

public class ReplaceSelection : ScriptableWizard
{
static GameObject replacement = null;
static bool keep = false;

public GameObject ReplacementObject = null;
public bool KeepOriginals = false;

[MenuItem("GameObject/-Replace Selection...")]
static void CreateWizard()
{
ScriptableWizard.DisplayWizard(
"Replace Selection", typeof(ReplaceSelection), "Replace");
}

public ReplaceSelection()
{
ReplacementObject = replacement;
KeepOriginals = keep;
}

void OnWizardUpdate()
{
replacement = ReplacementObject;
keep = KeepOriginals;
}

void OnWizardCreate()
{
if (replacement == null)
return;

Undo.RegisterSceneUndo("Replace Selection");

Transform[] transforms = Selection.GetTransforms(
SelectionMode.TopLevel | SelectionMode.OnlyUserModifiable);

foreach (Transform t in transforms)
{
GameObject g;
PrefabType pref = EditorUtility.GetPrefabType(replacement);

if (pref == PrefabType.Prefab || pref == PrefabType.ModelPrefab)
{
g = (GameObject)EditorUtility.InstantiatePrefab(replacement);
}
else
{
g = (GameObject)Editor.Instantiate(replacement);
}
g.transform.parent = t.parent;
g.name = replacement.name;
g.transform.localPosition = t.localPosition;
g.transform.localScale = t.localScale;
g.transform.localRotation = t.localRotation;
}

if (!keep)
{
foreach (GameObject g in Selection.gameObjects)
{
GameObject.DestroyImmediate(g);
}
}
}
}

原文:http://wiki.unity3d.com/index.php?title=ReplaceSelection
由四角钱翻译,转载请注明来自1vr.cn

发布于 :未分类

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注