Inserting Live & Respawn System With Character Controller

Today, a supposed to be easy to handle system caused me to sweat. As you may guess from the heading, it was about Character Controller component.

There are many ways that we can insert a live&death system to a platformer game. We can follow the y dimension of the transform.position and deduct a life if the player goes below a certain level. Likewise, we can insert an invisible game object just for using collision purposes. I have tried both ways and the second one actually was easier, so I am going to go with it.

Simply create a cube, place it underneath the play area, remove the Mesh Renderer component and check is Trigger true. I was actually thinking to do this with a plane, but Plane comes with a Mesh Collider. If you don’t know, a Box Collider will always be more efficient than a Mesh Collider in terms of computing power usage. Thus, it is better to stick with Box collider — so the cube.

Make sure to set the Z value of the collider same value as the game. To make the Player spawn again once he/she touches the area, I have tagged the Death collider as DeathZone.

And here comes my sweatining area. This was an easy challenge, and I was really surprised that my solution did not work initially. Somehow, the player was not spawning again at the position provided. I have literally checked everything: the trigger system was working, debug logged some codes to make sure that it runs until the end — which it did expectadly. So what was the problem? Here’s my inital code:

private void OnTriggerEnter(Collider other){if(other.tag == “DeathZone”){_lives — ;UIManager.Instance.UpdateLives(_lives);transform.position = _spawnPoint;}

Then, it hit me. I was using a Character Controller on the Player. Could it be the reason for blocking me to change the position of my Player? Just a quick google search approved me. It turns out that we need to disable the character controller for a moment before using transform position, and re-enable it afterwards. So here it is:

I have also created a Game Over visual in the UI Manager just for practice. Once the game finishes, it gives the result of our progress and enables us to restart the game if we want to.

Again, a day is over with new things learned!

Unity Developer