- Home /
Determine a prefab's "type"?
I am trying to create an Editor utility that will let me replace all the prefabs of a certain type in a parent object with a different prefab. The big problem I am running into is that I can't seem to find a way of determining what "type" a prefab is. Here is what I have so far. The problem part is the loop in ReplacePrefabs():
public class ReplacePrefabEditor : EditorWindow
{
Object removalObject;
Object replacementObject;
void OnGUI()
{
EditorGUILayout.BeginVertical();
removalObject = EditorGUILayout.ObjectField("Removal Object", removalObject, typeof(Object), true, null);
replacementObject = EditorGUILayout.ObjectField("Replacement Object", replacementObject, typeof(Object), true, null);
EditorGUILayout.EndVertical();
if (GUILayout.Button("Replace"))
{
if (!removalObject || !replacementObject)
{
Debug.LogError("Need to assign objects!");
return;
}
ReplacePrefabs();
}
}
[MenuItem("Prefab Helpers/Replace Prefabs")]
static void Init()
{
ReplacePrefabEditor window = (ReplacePrefabEditor)EditorWindow.GetWindow(typeof(ReplacePrefabEditor));
}
[MenuItem("Prefab Helpers/Replace Prefabs", true)]
static bool ValidateSelection()
{
return Selection.activeTransform != null;
}
void ReplacePrefabs()
{
Transform root = Selection.activeTransform;
int childCount = root.childCount;
for (int i = 0; i < childCount; ++i)
{
// determine if the current child is the same prefab type as removalObject
}
}
}
Answer by MarkFinn · Oct 04, 2012 at 06:17 AM
There's probably a better way, but as I need version control on my assets (Check version against server list of current versions) I use a very simple script for this. Just create a version of the script below and apply it to the assets.
using UnityEngine;
public class Version : MonoBehaviour {
public string type;
public int version;
public string Artist;
public string Source;
}
Answer by JanWosnitza · Oct 04, 2012 at 03:38 PM
This should do it:
void ReplacePrefabs()
{
var root = Selection.activeTransform;
var childrenToReplace = new List<Transform>();
// first collect children to replace
// (don't change a collection while enumerating over it!)
foreach ( Transform child in root )
{
if ( child.gameObject == removalObject )
childrenToReplace.Add( child );
}
// replace children
foreach ( var childToReplace in childrenToReplace )
{
var instance = Object.Instantiate( replacementObject );
instance.name = childToReplace.name;
Object.DestroyImmediate( childToReplace );
}
}
Your answer
Follow this Question
Related Questions
Reference to Scene Object Component in Prefab Editor, 'Type Mismatch'? 1 Answer
What is the type of my prefab? 2 Answers
Determine if game object is tyoepf One Prefab 3 Answers
The Script Equivilent of dragging a hierarchy of meshes over a preexisting prefab? 0 Answers
Why do prefabbed meshes go missing whenever I pull an update from Unity Collab? 0 Answers