Search code examples
unity-game-engineunityscriptunity3d-2dtools

Unity 2D respawning Instantiate issue


I am making a 2D Space-invaders style game and am having GREAT difficulty with respawning. What i want to happen is when the SpaceShip is hit, it gets Destroyed, e.x. Destroy();

But when i try to Instantiate() the Prefab of the SpaceShip it does the (clone)(clone) problem, so I am trying to Make an Empty GameObject run script that spawns in a Prefab of the SpaceShip, AND when it gets Destroy(); it respawns after 3 seconds. Much help appreciated, and i'm coding in JavaScript.


Solution

  • Have one class that instantiates every couple of seconds from a prefab. You will need to drag via the Editor the playerPrefab and you will need to specify the location for the spawn.

    public class Spawner : Monobehaviour
    {
        public GameObject playerPrefab;
    
        public void spawn()
        {
            Instantiate(playerPrefab, spawnPosition, spawnRotation);
        }
    }
    

    Then when your Player dies you can a SendMessage to the Spawner class.

    public class Player : MonoBehaviour
    {
        void Update()
        {
            if(hp <= 0)
            {
                 // Grab the reference to the Spawner class.
                 GameObject spawner = GameObject.Find("Spawner");
    
                 // Send a Message to the Spawner class which calls the spawn() function.
                 spawner.SendMessage("spawn");
                 Destroy(gameObject);
            }
        }
    }
    

    Same code in UnityScript

    Spawner.js

      var playerPrefab : GameObject;
    
      function spawn()
      {
          Instantiate(playerPrefab, spawnPosition, spawnRotation);
      }
    

    Player.js

      function Update()
      {
          if(hp <= 0)
          {
              // Grab the reference to the Spawner class.
              var spawner : GameObject = GameObject.Find("Spawner");
    
              // Send a Message to the Spawner class which calls the spawn() function.
              spawner.SendMessage("spawn");
              Destroy(gameObject);
          }
      }