I’m working on a Unity project and implemented a respawn system in my GameManager script. It handles respawning the player at the start position or the last activated checkpoint. Below is the relevant part of my code.
I’d really appreciate any feedback on:
Code structure and clarity.
Best practices or improvements I might have missed.
[SerializeField] private float respawnDelay;
private Vector3 initialSpawnPosition; // Store the original start position
private Vector3 currentRespawnPosition; // Keep track of where to respawn the player
private void Awake()
{
if (instance == null)
instance = this;
else
Destroy(gameObject);
initialSpawnPosition = playerPrefab.transform.position;
currentRespawnPosition = initialSpawnPosition;
}
public void UpdateRespawnPosition(Transform newRespawnPoint)
{
currentRespawnPosition = newRespawnPoint.position;
}
public void RespawnPlayer() => StartCoroutine(RespawnRoutine());
private IEnumerator RespawnRoutine()
{
yield return new WaitForSeconds(respawnDelay);
GameObject newPlayer = Instantiate(playerPrefab, currentRespawnPosition, Quaternion.identity);
player = newPlayer.GetComponent<Player>();
}