# Get GameObject which instantiated me in Unity

How can I get a GameObject from another GameObject? If I know, that the GameObject I want to get instantiated(using function Instantite()) the GameObject from which I want to get it.

If there is no solution, how can I get the direction in which should move the instantiated bullet? I mean should it be 1 or -1.

• Please, provide the code you have made so far, it will be simpler to help you. – Hellium Sep 19 '17 at 16:33
• Oh. Thank you very much, but I have really a lot of code and it will be pretty hard for you to go over it. So, you can view my question more generally. How can I get the GameObject which instantiated me? Or, how can I determine the direction for the bullet? I am talking about 2D here. – hellomates Sep 19 '17 at 16:41
• The object doing the instantiating should also set the initial state of the object it instantiates. That can include setting the direction of fire. – MichaelHouse Sep 19 '17 at 16:57
• Do you need a reference to the parent? If you use the Instantiate(object, position, orientation) form, you can spawn the bullet oriented so that its transform.forward already faces the direction that you want it to travel. – DMGregory Sep 19 '17 at 17:04

You must attach a script to the prefab you instantiate and "inject" a reference of the gameobject which has instantiated the prefab as follow :

public class Bullet : MonoBehaviour
{
public GameObject Gun ;
public Vector3 direction ;

public void Awake()
{
// You can't use Gun yet
}

public void Start()
{
if( Gun != null )
Debug.Log("I've been instiated by " + Gun.name ) ;
}

public void Update()
{
transform.Translate( direction ) ;
}
}

public class Gun : MonoBehaviour
{
public void Shoot()
{
GameObject instance = Instantiate( bulletPrefab ) ;
Bullet bullet = instance.GetComponent<Bullet>();
if( bullet != null )
{
bullet.Gun = gameObject;
bullet.Direction = transform.forward;
}
}
}

• Note that you can skip the GetComponent call and null check by just declaring the bulletPrefab parameter as public Bullet bulletPrefab. Then the Unity Inspector will enforce that the prefab you drag into this slot must have a Bullet component attached, and Instantiate<Bullet>(bulletPrefab) will give you a reference directly to that component in the spawned prefab, in the appropriate type. – DMGregory Sep 19 '17 at 17:02
• How can I do not show Bullet until I am done tweaking its inwards? – hellomates Sep 19 '17 at 17:04
• Your frame doesn't render until all update scripts have finished their work, so you don't need to do anything special to hide it, unless your setup work spans multiple frames using a coroutine or somesuch mechanism (this would be unusual for bullet firing) – DMGregory Sep 19 '17 at 17:08