Usually you would instantiate a clone of a prefab in a script using
var obj = (GameObject)Instantiate(....);
and than change it's parent using
var obj.transform.SetParent(...);
However I'm writing on a little editor script for instantiating prefabs over the menu entries that should keep their link to the prefab. I do it in a static
class like:
public static class EditorMenu
{
// This is a reference that I already have and is not null
privtae static Transform exampleParent;
[MenuItem("Example/Create Clone")]
private static void CreateClone()
{
var prefab = AssetDatabase.LoadAssetAtPath("Example/Path/myObject.prefab", typeof(GameObject));
var obj = (GameObject)PrefabUtility.InstantiatePrefab(prefab);
obj.transform.position = Vector3.zero;
obj.transform.rotation = Quaternion.identity;
Selection.activeGameObject = obj;
}
}
I had to use
(GameObject)PrefabUtility.InstantiatePrefab(prefab);
because Instantiate()
doesn't keep the link to the prefab but creates a clone.
So the above code works great so far and the object is inserted to the scene as if I would drag and drop it.
Now I would like to change this newly instantiated objects parent to parent
so I added the line
obj.transform.SetParent(exampleParent, true);
I also tried
obj.transform.parent = exampleParent;
But both throw an exception:
Setting the parent of a transform which resides in a prefab is disabled to prevent data corruption. UnityEngine.Transform:SetParent(Transform)
prefab
and thereby obj
are the topmost GameObject
of the prefab so I thought I am setting the parent of the whole instantiated object not any transform inside of the prefab hierachy.
How can I change the parent of a GameObject
instantiated via PrefabUtility.InstantiatePrefab
?
Update
A workarround I just tried was to actually use Instantiate
and do
var obj = Object.Instantiate(prefab, cancel.transform);
// remove the added "(clone)" suffix
obj.name = prefab.name;
obj.transform.SetParent(cancel.transform);
however as mentioned before this doesn't completely keep the prefb functionality intact .. so it only allows me to Revert
but not to Apply
changes. As workaround it might be good enough however since in my case I use it as a shortcut for instantiating a prefab which users are not really supposed to change later...
Instantiate()
can be called only from a MonoBehaviour? This is a static callGameObject.Instantiate()
. – z3nth10nInstantiatePrefab
sinceInstantiate
brakes the prefab functionality likeApply
changes – derHugo