X-Post from the Scripting forums - not sure if this is a better place for this type of question:
This simple Editor tool to instantiate Prefabs is doing so, but the instantiated objects are missing their connection to the prefab (aka not blue, updating prefab doesn’t show changes in copies).
[ExecuteInEditMode]
public class FixMazePrefabConnections : MonoBehaviour
{
foreach (GameObject maze in mazes)
{
// Instantiate blank maze
GameObject newMaze = PrefabUtility.InstantiatePrefab(blankMazePrefab) as GameObject;
}
}
Tweaked that for C#, no dice. Still no connection preserved:
// Instantiate blank maze
var newMaze = PrefabUtility.InstantiatePrefab(blankMazePrefab as GameObject) as GameObject;
//GameObject newMaze = PrefabUtility.InstantiatePrefab(blankMazePrefab as GameObject) as GameObject;
Oh… is your game object array coming into this operation without null game objects? When you do GameObject object = new GameObject(); it will create the game object there and then in your scene. (As if you instantiated)
No the List mazes is not null, I omitted that code. It’s a list of all the “maze” gameObjects in the Scene. A lot of these mazes have lost their Prefab connection for one reason or another, so I’m trying to write an editor tool to reconnect them.
What this loop is doing is creating a “copy” of each maze from it’s original Prefab, and then copying the individual maze component parameters over (hierarchy index, dimensions, position, rotation, so on).
At no point am I using GameObject obj = new GameObject();
I’m using exclusively PrefabUtility to instantiate new gameObjects, which is supposed to preserve the prefab connection.
Thank you for the suggestion, I implemented it and found that it worked successfully for instantiating a GameObject with it’s prefab connection preserved. However I discovered at other parts of the script were breaking the connection.
What I was doing: copying over all of the “previous” Scene object’s parameters to the newly instantiated prefab; things like the top-level transform position/rotation/scale down to the scale of certain child objects. I am fairly certain that these operations are what broke the connection of the newly instantiated mazes.
I discovered the PrefabUtility method ConnectGameObjectToPrefab() which solved all my problems. The updated loop is now: