Can not properly display the score on pong game
Hi i'm trying to make a simple pong game. Paddles, ball movements etc. works good but having trouble on displaying the score. When someone scores, their score starts increasing in every frame and after the invoke it goes back to the 0. I understand why is that happening but i couldn't find a proper solution. How can i do it?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class Ball : MonoBehaviour {
private Vector3 v ;
public Rigidbody rb;
private int score1 = 0, score2 = 0;
public Text t1;
public Text t2;
void Start()
{
rb = GetComponent<Rigidbody> ();
float rand = Random.Range (0.0f, 2.0f);
if (rand < 1.0f) {
v = new Vector3 (20.0f, 0.0f, 0.0f);
} else
{
v = new Vector3 (-20.0f, 0.0f, 0.0f);
}
}
void AfterScore()
{
SceneManager.LoadScene ("Pong");
}
void Update ()
{
rb.velocity = v;
if (transform.position.x < -25 )
{
Invoke ("AfterScore", 2.0f);
score1++;
t1.text = score1.ToString();
}
if(transform.position.x > 25)
{
Invoke ("AfterScore", 2.0f);
score2++;
t2.text = score2.ToString();
}
}
void OnCollisionEnter(Collision collision)
{
if (collision.collider.tag == "Paddle")
{
v.x = -v.x;
v.y += collision.transform.position.y;
}
else if (collision.collider.tag == "Wall")
v.y = -v.y;
}
}
Comment
Your answer
Follow this Question
Related Questions
Reserve ammo not displaying on UI 0 Answers
I Need Help Making A Speedometer Using UI Text. 0 Answers
BCE0022: Cannot convert 'String' to 'int' 0 Answers
Get height of text with given width. 0 Answers
Text not showing in build (but the rest of UI shows up) 1 Answer