Trying to destroy instances of Rigidbody2D
Been trying lots of things but no joy trying to Destroy individual instances of a cloned Rigidbody2D.
Error: MissingReferenceException: The object of type 'Rigidbody2D' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object. BallEmitter.Update () (at Assets/BallEmitter.cs:18)
Please can someone explain why this happening. Do I need to instantiate a new gameObject for each Rigidbody2D or something? Thanks.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class BallEmitter : MonoBehaviour {
public Rigidbody2D ball;
public float max;
public float min;
public List<Rigidbody2D> balls = new List<Rigidbody2D>();
void Start () {
InvokeRepeating ("ThrowBall", 0.0f, 0.8f);
}
void Update () {
foreach (var ball in balls) {
if (ball.transform.position.y < -4) {
Destroy (ball.gameObject);
}
}
}
void ThrowBall() {
Rigidbody2D ballInstance;
ballInstance = Instantiate (ball, transform.position, transform.rotation) as Rigidbody2D;
ballInstance.isKinematic = false;
ballInstance.AddForce (-Vector3.right * Random.Range(min,max));
balls.Add (ballInstance);
}
}
Answer by HenryStrattonFW · Feb 21, 2017 at 09:23 PM
This is because you are destroying the rigidbody components but not removing them from the list, so the next frame occurs, you are still trying to delete components that no longer exist.
Another note is that this code destroys the rigid body components and not the game object, so you may want to swap it to destroy the game object instead otherwise you will end up with logs of game objects in your scene that are never removed.
Thank you very much @HenryStrattonFW! That was foolish of me, I should have checked the line number - I thought it was unable to instantiate further game objects. But unless I am mistaken Destroy(ball.gameObject) should destroy the gameobject rather than the rigibody.
For anyone else viewing this question, don't forget to run the for loop in reverse when removing list items:
void Update () {
for (int i = balls.Count - 1; i > 0; i--) {
if (balls [i].transform.position.y < -4) {
Destroy (balls [i].gameObject);
balls.RemoveAt (i);
}
}
}
Your answer
Follow this Question
Related Questions
Bullet clones will not be destroyed. 2 Answers
destroying instantiated groups of objects 1 Answer
Is there any good sample code for shooting a projectile and collision detection? 0 Answers
Unable to delete instance of GameObject 0 Answers
Destroy GameObject in list then instantiate GameObject not working 1 Answer