Unity-销毁后如何重新生成游戏对象 [英] Unity - How to respawn a Gameobject after destroy

查看:733
本文介绍了Unity-销毁后如何重新生成游戏对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在团结一致来开发自己的游戏.在进球后,我已经创建了一个简单的游戏,就像足球一样,应该将球摧毁并重新出现在原来的位置上.

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;

}

但是它只能在第一次使用.然后第二次销毁后,它会显示一条错误消息,指出该对象已被删除,而您正在尝试访问已删除的对象或类似的对象.如果我在OntriggerEnter函数中使用destroy函数,则在第一次碰撞时会给出相同的错误.

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.

我该怎么办?请帮忙.

谢谢.

推荐答案

您正在尝试访问已删除的对象,因为您将脚本附加到了目标上,并且始终删除球,并且克隆副本永远也不会变成球(因此总是相同的球).

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).

如果将脚本附加到球上,您的脚本将起作用,因为在这种情况下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;
}

此外,BlueRaja的注释是您可以用来改进代码的重要内容:

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

  1. ball.GameObject可能只是ball,因为ball GameObject;
  2. 您要两次实例化结果,请检查此问题以了解更多信息关于它;
  3. 至少使用这段代码,没有理由让RespwanBall成为协程;
  4. 您拼错了重新生成".
  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'.

这篇关于Unity-销毁后如何重新生成游戏对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆