- Home /
How do I re-instantiate an object after it is destroyed from the scene?
I have a game object with a script attached called "playerController". My plan is to destroy this game object from another script and Instantiate it again after 3 seconds via IENumerator. I want the game object to be instantiated with the exact transform values it had during the start of the game.
The following code is from the other script that will destroy the game object with "playerController" attached and re-spawn it after 3 seconds.
public IENumerator Respawn()
{
destroy(playerController.gameObject);
yield return new WaitForSeconds (3.0f);
//This is where I respawn the game object with playerController script attached
}
Answer by jdean300 · Aug 17, 2016 at 07:56 AM
You're going to want to create a prefab for your player controller and then add this variable to your spawning script
public GameObject PlayerPrefab;
In the editor, drag and drop the prefab on that variable.
Then in your Respawn method:
GameObject go = Instantiate(PlayerPrefab);
playerController = go.GetComponent<PlayerController>();
Why does it not work for you?
(You could also make the PlayerPrefab Variable as Type PlayerController ins$$anonymous$$d of GameObject, then Instantiate will return a PlayerController object and you don't have to GetComponent)
And if you just use Instantiate it will spawn the object with the given position/rotation which is set in the prefab, so either you set your correct spawn position in the prefab or you make an additional vector3 variable with the spawn position and set the new create player controller object transform to your spawn position in the line after creating it.