-
Notifications
You must be signed in to change notification settings - Fork 3
20 Respawn

Now that the player's ship can be destroyed, our testing has become more difficult. It's always important to be able to jump into the game after making changes so you can test them out. Often a "God Mode" is required to set-up testing scenarios. We won't worry about that now, but what we do need is to be able to respawn if we happen to get destroyed while testing.
We have a generic Die behaviour that seems a good place to handle this. But remember that this script destroys the game object that it's attached to. Since it goes away, it won't be able to do any more work.
Instead, we'll do this in our PlayerChunks prefab. This is the thing that gets created when the player explodes. We'll make a Respawn script that we could later choose to apply to other destructible objects like UFOs or humans.
We're going to need these options:
- Respawn Prefab to instantiate (GameObject)
- Respawn Position (Transform)
- Respawn Delay Seconds (float)
-
Open the PlayerChunks prefab and add a new script called Respawn
-
Add these fields to the script They're public so we can set the values in the unity Inspector.
public GameObject RespawnPrefab; public Vector3 RespawnPosition; public float DelaySeconds = 5;
-
Add a function that does the respawn. This should first check that the prefab and location have been set to avoid possible errors later. This should also destroy the chunks object.
void RespawnNow() { if (RespawnPrefab != null) { if (RespawnPosition != null) { Instantiate(RespawnPrefab, RespawnPosition, Quaternion.identity); Destroy(gameObject); } } }
-
In the Start() function we now need to schedule this to happen after a delay. We can use the Invoke function for this.
Invoke("RespawnNow", DelaySeconds);
-
Save your script changes and back in Unity set the respawn position in the middle of your world. For me, this is Position X=500, Y=200, Z=500
-
Set the Respawn Prefab to your Player prefab
Give it a play test!