Search Unity

OnTriggerEnter2D score problem

Discussion in 'Scripting' started by kimi81, Feb 28, 2015.

  1. kimi81

    kimi81

    Joined:
    Feb 28, 2015
    Posts:
    6
    Hi. I'm having a problem with score script in a game I modified (from ,,Hat trick'' tutorial catch game).
    Difference is that you should be able to cath the bomb also..(without explosion)
    When I catch a regular ball I sometimes get 10 points, and sometimes I get -20 points.
    But I should get -20 points only when I catch the bomb...
    Everything is set up properly (coliders, tags, etc.)
    Please help...
    Here is the script:

    public Text scoreText;
    public int ballValue;
    public static int score;

    void Start () {
    score = 0;
    UpdateScore ();
    }
    void OnTriggerEnter2D () {
    if (GameObject.FindGameObjectWithTag ("bomb")) {
    score -= ballValue *2;
    UpdateScore ();
    }
    else if (GameObject.FindGameObjectWithTag ("ball")) {
    score += ballValue;
    UpdateScore ();
    }
    }
    UpdateScore () {
    scoreText.text = "Score:\n" + score;
    }
     
  2. DanielQuick

    DanielQuick

    Joined:
    Dec 31, 2010
    Posts:
    3,137
  3. Yemachu

    Yemachu

    Joined:
    Feb 1, 2015
    Posts:
    13
    When the object this script is attached to gets hit, it searches the world fo a bomb. Then if it can find one (A.K.A. there is an object tagged with "bomb" in the scene), your score is decreased. In case it couldn't find a bomb, it searches for ball; finding one nets you some points.

    I would assume that you want know what object triggered the function, rather than whether or not the scene contains a "bomb". Futhermore your UpdateScore seems to be missing a return-type; my compiler complains about it. In any case, here is some code which should do the trick:

    Code (CSharp):
    1. void OnTriggerEnter2D (Collider2D other)
    2. {
    3.     if (other.tag == "bomb")
    4.     {
    5.         //Penalty related stuff.
    6.     }
    7.     else if (other.tag == "ball")
    8.     {
    9.         //Score related stuff.
    10.     }
    11. }
     
  4. kimi81

    kimi81

    Joined:
    Feb 28, 2015
    Posts:
    6
    That does the trick. Thank you so much Yemachu, you're a life saviour...