Reputation: 39
So I want to instantiate an array of game objects via editor scripting. Now the problem is when I instantiate the prefab, it loses its parent in the hierarchy. When I'm instantiating like the script below, it works just fine:
for(int i = 0; i < 20; i++){ //_dTarget.halfLength; i++){
GameObject a = (GameObject)PrefabUtility.InstantiatePrefab(_dTarget.wallTile);
a.transform.parent = goTarget.transform;
}
but if I'm instantiating like this:
GameObject[] testG = new GameObject[20];
for(int i = 0; i < 20; i++){
testG[i] = _dTarget.wallTile;
}
for(int i = 0; i < 20; i++){ //_dTarget.halfLength; i++){
GameObject a = (GameObject)PrefabUtility.InstantiatePrefab(testG[i]);
a.transform.parent = goTarget.transform;
}
they lost their parent and instantiated outside the parent:
Any ideas why this happens?
Upvotes: 0
Views: 468
Reputation: 345
Before you can set the parent, you need to disconnect the new object from the prefab. You do this with PrefabUtility.DisconnectPrefabInstance.
Example:
for (int i = 0; i < 20; i++)
{
GameObject a = (GameObject)PrefabUtility.InstantiatePrefab(testG[i]);
PrefabUtility.DisconnectPrefabInstance(a);
a.transform.parent = goTarget.transform;
}
Update:
As of Unity 2018.3, DisconnectPrefabInstance
is obsolete. PrefabUtility.UnpackPrefabInstance can be used instead.
Upvotes: 2