C# Respawn and Score Problem
So I'm making a pong game and I'm trying to make the ball re-spawn and the score go up by 1 point every time it passes the paddle. Currently when the ball passes the paddle, the score goes up by one and keeps going up indefinitely and ball doesn't re-spawn.
Here is my code:
using UnityEngine; using System.Collections;
public class Score : MonoBehaviour {
public TextMesh currSco;
public GameObject ballPref;
public Transform paddleObj;
GameObject ball;
int score;
void Update ()
{
ball = GameObject.FindGameObjectWithTag("Ball");
currSco.text = "" + score;
}
void OnTriggerEnter(Collider other)
{
if (other.tag == "Ball")
{
score += 1;
Destroy(ball);
(Instantiate(ballPref, new Vector3(paddleObj.transform.position.x + 2, paddleObj.transform.position.y,0), Quaternion.identity) as GameObject).transform.parent = paddleObj;
}
}
}
I also have a "Ball" gameobject and i put my paddle under paddle obj in the script boxes in unity. Can someone please help?
Answer by Soraphis · Nov 10, 2015 at 05:23 PM
Why dont you just reset the ball position?
other.transform.position = new Vector3(......);
so you don't have to a) set the ball variable every frame. b) you don't need a reference to the ball at all. and you should do other.CompareTag("Ball")
and you shouldn't update the text each frame like this ... it would be enough to change the text after increasing the score
for the "why doesn't it work" I've got no clue. i could imagine it has something to do with your hierarchy. i dont get why you put your ball as a child of your paddle object...
What would I need to replace for the "other.transform.position = new Vector3()" code?. Also, the reason for making the ball a child of the paddle is so the ball moves with the paddle before the ball is shot out. Also isn't line 11 supposed to increase the text by the score? I should also say that it only happens when i put the paddle into the paddle obj slot under the score script.
This was the tutorial that I was using: https://www.youtube.com/watch?v=0YLDz$$anonymous$$kXl$$anonymous$$E
Your answer
Follow this Question
Related Questions
Unity/C# Respawn and score Problem 1 Answer
how to disable dontdestroyonload on a specific scene 2 Answers
Best Score Counter 0 Answers
Game highscore file writing 0 Answers