Every time our game starts, we should reset all its conditions to the same state. We already mentioned that resetting the starting position of the
Player game object would be a good start. Positions in the 3D world in Unity are described using Vector3 struct
. Go ahead and type Vector3
in the Scripting Reference for a better understanding. This is complex stuff, so don't worry if you can't get it. All you need to know now is that Vector3
is made up of three floats describing x, y, and z positions in the space.
Let's go forward and perform some code changes to set up the Player position. In PlayerController
, we will:
Vector3
type variable and call it startingPosition
in PlayerController
.startingPosition
value taken from the Player game object world space position in the Awake
method. This way, we will always store the initial position of the Player game object just after Unity starts executing the game.Start
method to StartGame
, as we will call it from the GameManager
from now.StartGame
method.You are feeling a bit confused now? We have carried out a lot of changes in one go. If you really feel lost now, here's what the first part of PlayerController
should look like (hopefully it will make you less anxious):
Now, inside the
GameManager StartGame
method, make sure you are calling:
PlayerController.instance.StartGame();
Time for testing. Save both scripts and come back to Unity. If you are getting any compiler errors, please go back and double-check everything. If you don't have any errors, that's great! Go ahead and press Play in Unity. Every time you hit the S button on the keyboard, the game will restart and the Player game object's position will be set back to its initial position.