Unity - How to respawn a Gameobject after destroy

2019-06-08 20:54发布

问题:

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.

回答1:

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


回答2:

You can try respawning the object by using this script -




using UnityEngine;
using System.Collections;

public class copy : MonoBehaviour
{




     [SerializeField]
    private GameObject prefab = null; // assign Cube prefab to this in Editor
    void Start()
    {
        // no need for a local prefab variable, nor a call to Resources.Load();
        for (int i = 0; i < 4; ++i)
        {
            Instantiate(prefab, new Vector3(0, i * 10, 0), Quaternion.identity); // you can directly assign position in Instantiate
        }
    }

}