- Home /
How to destroy and instantiate something without breaking this code
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.
Would just resetting the position of the ball work?
Answer by UnityVeris · Mar 02, 2018 at 05:00 AM
I'd suggest doing a lot of basic C# tutorials so that you know what it is that you are actually doing. There are quite a few issues with the above code, some of them very basic.
Nothing in that code destroys any object, so I'm assuming that you are destroying it elsewhere?
In such a situation it is not necessary to destroy an object, as destruction and instantiation can get heavy very quickly, it is better to use the gameObject.SetActive(bool) function instead if you need to temporarily disable an object.
Ya, xD, I burrowed this script from somewhere because unity physics doesn't bounce off walls, I also have the destroy function in another script, just thought of solution that works, thanks for the help.
Your answer
Follow this Question
Related Questions
Idle game currency converter 2 Answers
My Animation Loops 3/4 of the way through 3 Answers
my ladder script not working plz help me 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers