I have an enemy and a simple script on it (if hp <= 0
, then the enemy is destroyed). 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
Instantiate(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);
}
}
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.