Time for action – adding the Play Again button

The very last thing we need to do is to add a button to the end of the game so that the player can play again. Let's revisit our good friend GUI from the last few chapters.

  1. Add the OnGUI function to the HeartBounce script:
    function OnGUI(){
      if(hasLost){
       var buttonW:int = 100; // button width
       var buttonH:int = 50; // button height
       
       var halfScreenW:float = Screen.width/2; // half of the Screen width
       var halfButtonW:float = buttonW/2; // Half of the button width
    
       if(GUI.Button(Rect(halfScreenW-halfButtonW, Screen.height*.8, buttonW, buttonH), "Play Again"))
       {
          numHits = 0;
          hasLost = false;
          velocityWasStored = false;
          transform.position = Vector3(0.5,2,-0.05);
     rigidbody.velocity = Vector3(0,0,0); ...

Get Unity 4.x Game Development by Example Beginner's Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.