add score when an object leaves the boundary (Reference to space shooter)

Hi, I wanted to know how to get a score counted for when asteroids leave the game area in the space shooter tutorial (perhaps bonus points for dodging the asteroids), heres the scripts:

Game Controller

using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections;

public class Done_GameController : MonoBehaviour
{
    public GameObject[] hazards;
    public Vector3 spawnValues;
    public int hazardCount;
    public float spawnWait;
    public float startWait;
    public float waveWait;
   
    public GUIText scoreText;
    public GUIText restartText;
    public GUIText gameOverText;
   
    private bool gameOver;
    private bool restart;
    private int score;
   
    void Start ()
    {
        gameOver = false;
        restart = false;
        restartText.text = "";
        gameOverText.text = "";
        score = 0;
        UpdateScore ();
        StartCoroutine (SpawnWaves ());
    }
   
    void Update ()
    {
        if (restart)
        {
            if (Input.GetKeyDown (KeyCode.R))
            {
                SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
            }
        }
    }
   
    IEnumerator SpawnWaves ()
    {
        yield return new WaitForSeconds (startWait);
        while (true)
        {
            for (int i = 0; i < hazardCount; i++)
            {
                GameObject hazard = hazards [Random.Range (0, hazards.Length)];
                Vector3 spawnPosition = new Vector3 (Random.Range (-spawnValues.x, spawnValues.x), spawnValues.y, spawnValues.z);
                Quaternion spawnRotation = Quaternion.identity;
                Instantiate (hazard, spawnPosition, spawnRotation);
                yield return new WaitForSeconds (spawnWait);
            }
            yield return new WaitForSeconds (waveWait);
           
            if (gameOver)
            {
                restartText.text = "Press 'R' for Restart";
                restart = true;
                break;
            }
        }
    }
   
    public void AddScore (int newScoreValue)
    {
        score += newScoreValue;
        UpdateScore ();
    }
   
    void UpdateScore ()
    {
        scoreText.text = "Score: " + score;
    }
   
    public void GameOver ()
    {
        gameOverText.text = "Game Over!";
        gameOver = true;
    }
}

Destroy by Boundary script

using UnityEngine;
using System.Collections;

public class Done_DestroyByBoundary : MonoBehaviour
{
    void OnTriggerExit (Collider other)
    {
       
            Destroy (other.gameObject);

    }
}

Destroy by contact script

using UnityEngine;
using System.Collections;

public class Done_DestroyByContact : MonoBehaviour
{
    public GameObject explosion;
    public GameObject playerExplosion;
    public int scoreValue;
    public int scoreValue2;
    private Done_GameController gameController;
    private Done_DestroyByBoundary destroyBoundary;

    void Start ()
    {
        GameObject gameControllerObject = GameObject.FindGameObjectWithTag ("GameController");
        if (gameControllerObject != null)
        {
            gameController = gameControllerObject.GetComponent <Done_GameController>();
        }
        if (gameController == null)
        {
            Debug.Log ("Cannot find 'GameController' script");
        }
    }

    void OnTriggerEnter (Collider other)
    {
        if (other.tag == "Boundary" || other.tag == "Enemy")
        {
            return;
        }

        if (explosion != null)
        {
            Instantiate(explosion, transform.position, transform.rotation);
        }

        if (other.tag == "Player")
        {
            Instantiate(playerExplosion, other.transform.position, other.transform.rotation);
            gameController.GameOver();
        }
       
        gameController.AddScore(scoreValue);
        Destroy (other.gameObject);
        Destroy (gameObject);
    }
    void OnTriggerExit (Collider other)
    {

        {
            if (other.tag == "Enemy") {
                return;
            }
            gameController.AddScore (scoreValue2);


        }

    }

}

Player controller script

using System.Collections;

[System.Serializable]
public class Done_Boundary
{
    public float xMin, xMax, zMin, zMax;
}

public class Done_PlayerController : MonoBehaviour
{
    public float speed;
    public float tilt;
    public Done_Boundary boundary;

    public GameObject shot;
    public Transform shotSpawn;
    public float fireRate;
    
    private float nextFire;
   
    void Update ()
    {
        if (Input.GetButton("Fire1") && Time.time > nextFire)
        {
            nextFire = Time.time + fireRate;
            Instantiate(shot, shotSpawn.position, shotSpawn.rotation);
            GetComponent<AudioSource>().Play ();
        }
    }

    void FixedUpdate ()
    {
        float moveHorizontal = Input.GetAxis ("Horizontal");
        float moveVertical = Input.GetAxis ("Vertical");

        Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);
        GetComponent<Rigidbody>().velocity = movement * speed;
       
        GetComponent<Rigidbody>().position = new Vector3
        (
            Mathf.Clamp (GetComponent<Rigidbody>().position.x, boundary.xMin, boundary.xMax),
            0.0f,
            Mathf.Clamp (GetComponent<Rigidbody>().position.z, boundary.zMin, boundary.zMax)
        );
       
        GetComponent<Rigidbody>().rotation = Quaternion.Euler (0.0f, 0.0f, GetComponent<Rigidbody>().velocity.x * -tilt);
    }
}

and figured it out by adding scoreValue2 to score for when asteroids objects leave the boundary !

btw, sorry if my english is not that great.

OK, I haven’t gone through this tutorial, but you’ve done a great job collecting all the relevant scripts (and posting them correctly — you’d be amazed how many new forum users mess that up).

Looking at the last script above, line 42 seems very likely to me. Here it is again:

      gameController.AddScore(scoreValue);

The “gameController” referenced here is a property defined on line 9, which refers to the Done_GameController script on some other object. It’s found via the code in the Start method.

So, you’d need to copy this property and this Start method into your Done_DestroyByBoundary script.

Then in OnTriggerExit, in addition to calling Destroy as it does now, you’d also call gameController.AddScore.

Does all that make sense?

yes :slight_smile: i found out by playing around with the script (destroybycontact), and added scoreValue2 , thanks

using UnityEngine;
using System.Collections;

public class Done_DestroyByContact : MonoBehaviour
{
    public GameObject explosion;
    public GameObject playerExplosion;
    public int scoreValue;
    public int scoreValue2;
    private Done_GameController gameController;
    private Done_DestroyByBoundary destroyBoundary;

    void Start ()
    {
        GameObject gameControllerObject = GameObject.FindGameObjectWithTag ("GameController");
        if (gameControllerObject != null)
        {
            gameController = gameControllerObject.GetComponent <Done_GameController>();
        }
        if (gameController == null)
        {
            Debug.Log ("Cannot find 'GameController' script");
        }
    }

    void OnTriggerEnter (Collider other)
    {
        if (other.tag == "Boundary" || other.tag == "Enemy")
        {
            return;
        }

        if (explosion != null)
        {
            Instantiate(explosion, transform.position, transform.rotation);
        }

        if (other.tag == "Player")
        {
            Instantiate(playerExplosion, other.transform.position, other.transform.rotation);
            gameController.GameOver();
        }
     
        gameController.AddScore(scoreValue);
        Destroy (other.gameObject);
        Destroy (gameObject);
    }
    void OnTriggerExit (Collider other)
    {
        if (other.tag == "Enemy") {
            return;
        }
        gameController.AddScore (scoreValue2);


    }
}
1 Like

Please don’t do that! You asked a great question. And now it’s gone. :frowning:

When you have something to add to your original post, just reply to the thread, or if it’s a minor correction or addendum, edit the post and add that. But please never delete a legitimate question or comment. Doing so makes it impossible for others to learn from your contribution.

1 Like

you are right, i re-added :slight_smile:

i have another problem, after the player is destroyed, the score keeps adding up as the asteroids exit the game area, how can i stop the score as soon as the player is destroyed?

Well, you’re calling the AddScore method of your Done_GameController script (lines 68-72 of the first script above). So you need to update that method, so it’s smart enough not to keep adding to the score when the game is over.

Fortunately, it already knows when the game is over (it has a gameOver field). So you probably just need to add this line to the start of AddScore:

    if (gameOver) return;

thanks, i been thinking about 1 more thing, if i want say spawn different shape asteroids after say 5 minutes if the player survive, how to go around doing that? there’s 4 different shape asteroids in this tutorial that spawn from the start, but if i want after 5 minutes replace those 4 with different ones, which way to go?

thanks!!

Hmm. For this I guess you would need to add a field to the game manager (Done_GameController) that keeps track of what time (Time.time value) the game started. And then whatever’s spawning the asteroids can check that (or check some public method that uses that) to decide what kind of asteroids to spawn.

But this is getting pretty advanced… I don’t think it’s going to be productive to have people leading you through it step by step at this point.

My advice would be to declare victory on this one, and move on to the next tutorial. Also be sure you’re including some focused C# tutorials like these. As you do them, you’ll pick up more and more skills that will enable you to figure stuff like this out on your own!