Unity - How to respawn a Gameobject after destroy

后端 未结 2 359
我寻月下人不归
我寻月下人不归 2021-01-14 19:39

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 p

2条回答
  •  北恋
    北恋 (楼主)
    2021-01-14 20:02

    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:

    IEnumerator RespwanBall() {
        Destroy (ball.gameObject);
        ball = (GameObject)Instantiate (ball, ballPosition, Quaternion.identity);
        yield return null;
    }
    

    Also, BlueRaja's comments are important things that you could use to improve your code:

    1. ball.GameObject could just be ball, since ball is a GameObject;
    2. You're casting the result from Instantiate twice, check this question to know more about it;
    3. At least with this piece of code, there's no reason for RespwanBall to be a coroutine;
    4. You mispelled 'Respawn'.

提交回复
热议问题