Search code examples
c#unity-game-enginecountercounting

Script stops counting after 1 count


It has been 4-5 days since i started practicing Unity and c#. I am pretty ameteur. I have an issue that i could not figure out. I am trying to code that simple 2D ping-pong like game. Every time player misses the ball i instantiate the ball and count the score. But even the ball is instantiated everytime , game stops increasing the scores after 1 time.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ballmove : MonoBehaviour
{
    private Rigidbody2D rb;
    public float speed;
    public GameObject top;
    private Vector2 direct;
    public int p2;
    public int p1;
    public Text scoretext;
    public Text scoretext2;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        speed = 3f;
        InvokeRepeating("speedUp", 10f, 10f);

        p1 = 0;
        p2 = 0;
    }

    void Update()
    {
        if (rb.velocity == new Vector2(0f, 0f))
        {
            if (Input.GetKeyDown(KeyCode.Space))
            {
                rb.velocity = new Vector2(2f, 1f) * speed;
            }
        }
    }

    void OnTriggerEnter2D(Collider2D other)
    {
        if (other.gameObject.tag == "finish2")
        {
            Debug.Log("This if is working");

            p2++;

            Instantiate(top, new Vector2(-6.4f, -0.2f), Quaternion.identity);
            Destroy(this.gameObject);

            updateScore2();
        }
        if (other.gameObject.tag == "finish")
        {
            p1++;

            Instantiate(top, new Vector2(6.32f, -0.2f), Quaternion.identity);
            Destroy(this.gameObject);

            updateScore();
        }
    }

    void updateScore()
    {
        scoretext.text = p1.ToString();
    }
    void updateScore2()
    {
        scoretext2.text = p2.ToString();
    }
    void speedUp()
    {
        direct = rb.velocity.normalized;
        rb.velocity += direct * 2f;
    }
}

Both my p1 and p2 (scores) just increases 1 time. But they are under the same condition with

instantiate and everytime one of the players scores, the instantiate works but p1 and/or p2 stay at

the value 1.

Thanks.


Solution

  • I can't comment to ask this because I have <50 rep but - is this script attached to the ball itself?

    If so, that is the problem. The ball instantiates carrying a score of 0, and when it is destroyed, simply writes a score of 1 again to the display score.

    Try changing the definition of the scores to static:

    public static int p2;
    public static int p1;
    

    EDIT: I missed this the first time I looked, but, you also set the score to 0 in the Start() function. You'll need to remove that, and instead initialise them to be 0 in their original definition:

    public static int p2 = 0;
    public static int p1 = 0;