I'm Using unity for developing my game. I've created a simple game just like football after scoring a goal the ball should be destroyed and then reappear at its original place.
I've attached this script to my goal object.
public GameObject ball;
Vector3 ballPosition = new Vector3 (4.51f,0.10f,-3.78f);
void OnTriggerEnter(Collider other)
{
StartCoroutine ("RespwanBall");
}
IEnumerator RespwanBall() {
GameObject clone = (GameObject)Instantiate (ball, ballPosition, Quaternion.identity) as GameObject;
Destroy (ball.gameObject);
yield return null;
}
But it works only for the first time. and then After second destroy it gives an error saying that the object is already deleted and you are trying to access a deleted object or something like that. And if I use the destroy function in the OntriggerEnter
function it gives the same error during the first collision.
How can I do it? Please Help.
ThankYou.
You are trying to access the deleted object because you attached the script to the goal and you are always deleting the ball, and your clone never becomes the ball (so it's always the same ball).
Your script would work if it was attached to the ball, because in this case the
ball
would be itself, therefore the destruction method would always be activated in the active ball.If you want to attach it to the goal, make sure to update your clone to be the active ball:
Also, BlueRaja's comments are important things that you could use to improve your code:
ball.GameObject
could just beball
, sinceball
is aGameObject
;