- Home /
Making Pong in Unity
I am trying to make pong in unity . The problem is that I am not able to Instantiate after deleting the ball. please correct my code scoreboard.cs-
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class scoreboard : MonoBehaviour {
public GameObject prefabBall;
public Text scoreP1;
public Text scoreP2;
public int P1 = 0;
public int P2 = 0;
public GameObject ball;
public Rigidbody2D rb2D;
// Use this for initialization
void Start () {
ball = GameObject.FindGameObjectWithTag ("ball");
prefabBall = GetComponent<GameObject> ();
ball.AddComponent<Rigidbody2D> ();
if(GameObject.FindGameObjectWithTag ("ball")){
Debug.Log ("ball found");
}
}
// Update is called once per frame
void Update () {
GameObject Ball;
ball = GameObject.FindGameObjectWithTag ("ball");
if (ball.transform.position.x < -10.6f) {
P2++;
Destroy (ball);
Ball = Instantiate (prefabBall,new Vector2(0f,0f),Quaternion.identity);
Ball.AddComponent<Ball> ();
// Ball.AddComponent<Rigidbody2D> ();
} else if (ball.transform.position.x > 10.6f) {
P1++;
Destroy (ball);
Ball = Instantiate (prefabBall,new Vector2(0f,0f),Quaternion.identity);
Ball.AddComponent<Ball> ();
// Ball.AddComponent<Rigidbody2D> ();
}
//Instantiate (ball,new Vector2(0f,0f),Quaternion.identity);
scoreP2.text = P2.ToString();
scoreP2.text = P1.ToString ();
}
/*void OnCollisionEnter2D(Collision2D coll){
Destroy(ball);
Debug.Log ("Ball destroyed");
}*/
}
ball.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Ball : MonoBehaviour {
[SerializeField]
Rigidbody2D rb ;
[SerializeField]
float minSpeed = 2f,maxSpeed = 10f;
float velocity =0;
int count = 0;
//for audio
public AudioSource bip;
// Use this for initialization
void Start () {
rb = GetComponent<Rigidbody2D> ();
bip = GetComponent<AudioSource> ();
velocity = Random .Range(minSpeed, maxSpeed);
float service = Random .Range(0f, 2f);
Vector2 direction;
float angle= Mathf.Deg2Rad*0;
if(service>=1f){
angle = Random.Range (50, 310);
}else if (service<1f){
angle = Random.Range (130, 230);
}
direction = new Vector2 (Mathf.Cos (angle*Mathf.Deg2Rad), Mathf.Sin (angle*Mathf.Deg2Rad));
rb.AddForce (direction * velocity, ForceMode2D.Impulse);
}
// Update is called once per frame
void Update () {
}
void OnCollisionEnter2D(Collision2D col){
bip.Play ();
velocity *= 1.03f;
Debug.Log (transform.position.x);
}
}
Project Link :link text
Comment
Answer by tormentoarmagedoom · Jan 30, 2019 at 12:11 PM
Good day.
Look this:
Ball.AddComponent<Ball>
You are using the same name for an object variable and for the class (script). This will give you problems for sure... change one of the names.
Bye!
Your answer
Follow this Question
Related Questions
How to move a object side to side using mouse? js3 0 Answers
Need Help making Pong AI beatable 1 Answer
2D Pong Ball Not Reflecting Off Walls "Exactly" 1 Answer
Unity pong online multiplayer 0 Answers
End a game? 2 Answers