0
votes

I am using Prefabs for game levels. To debug a level I just drag the prefab into Hierarchy view and press [play].

To test level I need an option to replay the prefab, but since I drop it into Hierarchy I need a way to grab the original prefab and Instantiate it again. (and destroy current active prefab).

To find current Active Prefab on Play I just use:

GameObject gameObj= GameObject.FindWithTag("Level");

How do I get the original Prefab and Instantiate it again when pressing 'REPLAY' (button to reload prefab).

I did try to use GetCorrespondingObjectFromOriginalSource https://docs.unity3d.com/ScriptReference/PrefabUtility.GetCorrespondingObjectFromOriginalSource.html This will always return null.

1

1 Answers

1
votes

Objects in the scene don't have references to the prefabs they come from at runtime. Unity breaks these references when the scene is run (or built). PrefabUtility is an editor-only class for writing editor code.

If you want to do something similar, I'd suggest creating another script that has a reference to the prefab you wish to spawn in. This script can then instantiate that prefab in as a child when the game starts (in Awake or Start) and could have a method on it for destroying the instance and instantiating it again when you want to restart your level.