0
votes

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?

1
You know that you can instantiate an object and set it's parent in one call ? Instantiate(Object original, Vector3 position, Quaternion rotation, Transform parent)Mateusz
Of course I know that ! But this thing is different. It's editor scripting.Ali Akbar
did you try transform.SetParent method instead of assigning parent?Umair M
I already tried that and the result is same as before @UmairMAli Akbar

1 Answers

2
votes

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.