I am making a pong like game and when the ball hits the left wall or the right wall, I destroy the gameobject and instantiate it again on position (0, 0, 0) and add speed to it. However, the instantiated prefab clones don’t collide with the other walls and paddles like the original object.
The walls are static (bodyType) and the paddles are dynamic, and all elements have RigidBody2D components.
This is the excerpt of code where I instantiate the new GameObject:
void OnCollisionEnter2D(Collision2D coll) {
Debug.Log("Hello");
if (coll.gameObject.tag == "LeftLimit" || coll.gameObject.tag == "RightLimit") {
if (coll.gameObject.tag == "LeftLimit") {
rightScore++;
rightScoreText.text = rightScore.ToString();
}
else if (coll.gameObject.tag == "RightLimit") {
leftScore++;
leftScoreText.text = leftScore.ToString();
}
Destroy (gameObject);
GameObject newBall = Instantiate (ballPrefab, new Vector3(0,0,0), Quaternion.identity) as GameObject;
rb = newBall.GetComponent<Rigidbody2D>();
collider = newBall.GetComponent<Collider2D>();
Debug.Log(rb.bodyType);
Debug.Log(collider);
rb.velocity = new Vector2(Random.Range(-1.0f, 1.0f), Random.Range(-1.0f, 1.0f));
rb.velocity = rb.velocity.normalized * 15;
}
}
I do realize I can just change the transform of the Ball GameObject so I don’t need to use Destroy and Instantiate. However, I will need Instantiate when I implement more of the project so I didn’t want to brush over this.