- Home /
Script stops counting after 1 count.
Hello. 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"){
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.
Answer by kalibcrone · Jul 23, 2017 at 06:13 PM
Each time you instantiate the GameObject ball, your Start() method is being called. Being that in your Start method, you have p1 = 0; p2 = 0; you effectively reset the score each time. So, once they score, it goes up by 1, and is printed as a string to scoreText, then set back to 0, and repeat.
Instead of Destroying and instantiating your ball again, you should just disable it, or turn off its mesh (in this case, you will need to disable it's mesh as it seems that this script is attached to the ball itself) and then reset it's values, such as it's speed value and it's position.
EDIT: OR, instead, more simply, in your Start function, instead of setting p1 = 0; p2 = 0; set p1 = Int32.Parse(scoreText1.text); and p2 = Int32.Parse(scoreText2.text); This way instead of the score getting set to 0 each time, it is getting set to the previously recorded score.
Good luck!
Your answer
Follow this Question
Related Questions
Run time counter 1 Answer
Only tagged objects raise counter 1 Answer
Making something happen only for one second during an Update function? 1 Answer
Creating an up and down counter 2 Answers