Search Unity

Adding Lives to 2D Shooter tutorial

Discussion in 'Community Learning & Teaching' started by teknophyl, Jul 20, 2014.

  1. teknophyl

    teknophyl

    Joined:
    Jun 22, 2014
    Posts:
    51
    I'm trying to extend the 2D shooter tutorial by adding number of lives to the GameOver condition.

    I've got the GUI text working and incremented but my ship isn't acting correctly.

    I extended GameController.cs with a new public variable, livesLeft

    Code (CSharp):
    1.  
    2. public int livesLeft;
    3. public GUIText numOfLivesLeft;
    Then added a new method called UpdateLives:

    Code (CSharp):
    1.  void UpdateLives()
    2.     {
    3.         numOfLives.text = "x " + livesLeft;
    4.     }
    And set the variables in Start:

    Code (CSharp):
    1. livesLeft = 3;
    2. UpdateLives();
    Finally, I modified the Update method, thinking I could just recreate the Player object:
    Code (CSharp):
    1. void Update()
    2.     {
    3.  
    4.  
    5.         if (restart)
    6.         {
    7.             if (Input.GetKeyDown(KeyCode.R))
    8.             {
    9.                 Application.LoadLevel(Application.loadedLevel);
    10.             }
    11.         } else
    12.         {
    13.             UpdateLives();
    14.  
    15.             if (livesLeft != 0)
    16.             {
    17.                 Instantiate(player, player.transform.position, player.transform.rotation);
    18.             }
    19.         }
    20.     }
    I then went over to DestroyByContact and intended to update the OnTriggerEnter method like this:
    Code (CSharp):
    1. if (other.collider.tag == "Player") {
    2.  
    3.             Instantiate (playerExplosion, other.transform.position, other.transform.rotation);
    4.  
    5.  
    6.             gameController.livesLeft -= 1;
    7.             if (gameController.livesLeft == 0)
    8.             {
    9.                 gameController.GameOver();
    10.             }
    11.  
    12.         }
    Except it doesn't work; my livesLeft label gets some crazy value (-227 or some such), and I get the following console exception:

    MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it.
    Your script should either check if it is null or you should not destroy the object.
    GameController.Update ()

    Can someone point me in the right direction on what I'm doing wrong?
     
  2. teknophyl

    teknophyl

    Joined:
    Jun 22, 2014
    Posts:
    51
    I managed to get it working. Now to get the timer on respawn functioning correctly... :)
     
  3. Shortmeister

    Shortmeister

    Joined:
    Jan 29, 2016
    Posts:
    1
    Hi there, I'm trying to add lives myself and have hit a few hurdles. Do you have a copy of the completed code you added?

    Thanks in advance.