- Home /
How to replace a GameObject by script and keep references to it intact?
I have an editor script that can replace a GameObject with another by instantiating a Prefab.
Unfortunately this invalidates references to the old GameObject. How can I keep these references intact or at least restore them to reference the new GameObject?
Some context if needed: The script is used to exchange different PrefabVariants of the same Prefab easily while keeping some of the configuration (e.g. replacing the hat a character is wearing with a new model but keeping its color).
And the relevant part of the script:
Object prefab = AssetDatabase.LoadAssetAtPath(path, typeof(GameObject));
var newGO = (GameObject)PrefabUtility.InstantiatePrefab(prefab, oldGO.transform.parent);
Undo.RegisterCreatedObjectUndo(newGO, "Replace by " + type);
// ... Copy transform and other properties from oldGO to newGO ...
Undo.DestroyObjectImmediate(oldGO);
Your answer
![](https://koobas.hobune.stream/wayback/20220612233315im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Unity Inspector Choose C# object from list 0 Answers
Bug with displaying components in Inspector after hideFlags.NotEditable? 1 Answer
Detecting when a component has been pasted onto an inactive object 1 Answer
BCE0044 erro only shows when trying to build .apk 0 Answers
EditorGUILayout.Foldout doesn't work and occur blank error. 0 Answers