Home > Back-end >  spawn prefab after killing enemie
spawn prefab after killing enemie

Time:10-13

I have an enemy and simple script on it (if hp <= 0, then the enemy is destroy) I want the enemy to spawn a prefab after death, which allows you to pick up a gun in the inventory, but if you create it through Instantie(pistolprefab, GameObject.transform); then the gun is created as a "child" of the enemy and is also destroyed with the enemy

public GameObject snipprefab;
public GameObject pistolprefab;
public GameObject rocketlauncherprefab;



public int TypeOfGun = 0;
private bool gunSpawned = false;

public static float HP = 10;

public void Start()
{

}
public void AddDamage(float damage)
{
   HP -= damage;
   if (HP <= 0)
{
if (EnemyHealth.HP <= 0 && gunSpawned == false)
{
   switch (TypeOfGun)
   {
      case 1:
      Instantiate(pistolprefab, gameObject.transform);
      break;
      case 2:
      Instantiate(snipprefab, gameObject.transform);

      break;
      case 3:
      Instantiate(rocketlauncherprefab, gameObject.transform);

      break;
   }
   gunSpawned = true;
}
Destroy(gameObject);

}
}

the project needs to be completed as soon as possible, now I'm doing it for the second day in a row and my head is not working

p.s sorry for my bad english

CodePudding user response:

Just move your object to the different parent using SetParent() on your new game object's transform component:

GameObject temp = Instantiate(pistolprefab, gameObject.transform);

temp.transform.SetParent(null); // set parent to null if you don't want it to have a parent

Make sure to do that, before the original object is destroyed.

  • Related