How can I Instantiate a parent object in a child object?
I am creating a code that makes an enemy drop items, but the problem is that I dont want to instantiate the item as a child of the enemy
For example:
Enemy1 <-- Parent (Then, when its killed generates a child object, which is the item)
Item <-- Child of enemy1
And since the enemy1 was killed, it will be destroyed, but the problem is that it also destroys the Item that it drops, since its a child from enemy.
The code I am using for this is:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyControl : MonoBehaviour , ILivingThing{
public Enemy thisEnemy;
void Update () {
//Some artificial intelligence here...
Damage(1);
}
public void Damage(float damageAmt){ //Implemented from ILivingThing
thisEnemy.Damage (damageAmt);
if (thisEnemy.Health <= 0) {
dropItem ();
Kill ();
}
}
public void Heal(float healAmt){ //Implemented from ILivingThing
thisEnemy.Heal (healAmt);
}
public void Kill(){ //Implemented from ILivingThing
thisEnemy.Kill ();
//Destroy (gameObject);
}
void dropItem(){
GameObject Item = Instantiate (Resources.Load ("Prefabs/Items/Item1"), gameObject.transform) as GameObject;
Item.GetComponent<ItemControl> ().thisItem = new Item1();
}
}
How can I Instantiate a GameObject on "top of hierarchy" to get rid of this problem?
Answer by Cycy · Mar 01, 2017 at 01:45 PM
Hi, here the doc https://docs.unity3d.com/ScriptReference/Object.Instantiate.html.
It says :
public static Object Instantiate(Object original, Transform parent);
So if you want to instantiate your GameObjet on top of hierarchy (ie : a GameObject with no Parent), your dropItem() could be :
GameObject Item = Instantiate (Resources.Load ("Prefabs/Items/Item1"), null) as GameObject;
In a general way :
transform.parent = null; // will move the transform to the root of your scene.
Hope it will help you,
bye :)
Thank you very @Cycy !
I've checked the unity's documentation, but I didn't know how to implement this: "By default the parent of the new object will be null, so it will not be a "sibling" of the original. However, you can still set the parent using the overloaded methods."
Now, I understood it, its just about setting null the transform.
Thanks!!
Your answer
Follow this Question
Related Questions
Cannot get my double jump to work (2D) , 0 Answers
After upgrading from 2019.1.7 to 2019.4.8, some graphics on iOS are not displaying correctly 0 Answers
2D box collider always detecting player,2D Box colliders detecting player when he is not there 1 Answer
Unity Linerenderer jaggy lines 0 Answers
How to get collision on a Collider with "is Trigger" on? 0 Answers