Search code examples
c#unity-game-engineinstantiationgameobject

How do I Instantiate an object at the transform position of another GameObject in Unity?


Sorry, I know this is super basic! Finished my first Unity course and am working on my first game and just want a hockey puck to spawn at the position of the PlayerPuckSpawn GameObject in the hierarchy after the opponent scores a goal. Currently just writing a method for when the goal is scored.

    public void EnemyGoalScored()
        {
            StartCoroutine(EnemyScored());
            Destroy(gameObject);
            Instantiate(gameObject, PlayerPuckSpawn.transform.position); 
        }

This is in the script associated with the puck, so the gameObject refers to the puck. Just can't remember how to write the script part that tells the puck to spawn at the position of the PlayerPuckSpawn, which is a GameObject in the hierarchy. I know it's super basic, but I've been searching online and through my class notes and can't find it. Super thanks to anyone who can help! :)


Solution

  • One variant of the Instantiate method has a location and rotation parameter. to use the world coordinates of the calling item, do:

    Instantiate(prefab_to_inst,transform.position,transform.rotation);
    

    If you do not want to copy the rotation, can also use default rot:

    Instantiate(prefab_to_inst,transform.position,Quaternion.identity);
    

    To copy the position of any item, prepend the reference before transform to use that item's location.

    If you have GameObject puckspawn; defined and filled,

    Instantiate(prefab_to_inst,puckspawn.transform.position,puckspawn.transform.rotation);