I have a script for a basic game(Pong) where the ball bounces off the walls, I want to make it so when the ball hits one of the walls it gets destroyed and instantiates in the middle of the board, when I try I get an error because temporarily the ball doesn’t exist so the script freaks out, how should I fix this, here’s the script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class makeballmove : MonoBehaviour
{
[SerializeField]
[Tooltip("Just for debugging, adds some velocity during OnEnable")]
private Vector3 initialVelocity;
bool plswork;
public Transform spawnpoint;
[SerializeField]
private float minVelocity = 6.0f;
private Vector3 lastFrameVelocity;
private Rigidbody rb;
private void OnEnable()
{
plswork = true;
rb = GetComponent<Rigidbody>();
rb.velocity = initialVelocity;
}
private void Update()
{
if (plswork == true) {
rb.AddForce (transform.right * 3.0f);
}
lastFrameVelocity = rb.velocity;
}
private void OnCollisionEnter(Collision collision)
{
Bounce(collision.contacts[0].normal);
if (collision.gameObject.name == "Player2") {
plswork = false;
}
if (collision.gameObject.name == "Goal1") {
Instantiate (gameObject);
}
if (collision.gameObject.name == "Goal2") {
Instantiate (gameObject);
}
}
private void Bounce(Vector3 collisionNormal)
{
var speed = lastFrameVelocity.magnitude;
var direction = Vector3.Reflect(lastFrameVelocity.normalized, collisionNormal);
Debug.Log("Out Direction: " + direction);
rb.velocity = direction * Mathf.Max(speed, minVelocity);
}
}
This is the script that makes the ball move and bounce off walls, when I destroy the ball and then Instantiate it the editor comes up with this error, NullReferenceException, object reference not set to instance of object. Any help is welcome, thx ps I’m new… and bad at coding, thanks for any help.