Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Prefab instantiate from a different position that the one set inside the Instantiate function

Discussion in 'Prefabs' started by unity_46EAE4DD44B7F2470F16, Feb 6, 2022.

  1. unity_46EAE4DD44B7F2470F16

    unity_46EAE4DD44B7F2470F16

    Joined:
    Oct 20, 2021
    Posts:
    1
    I want to instantiate prefab copies from the position of the player but instead whenever I click the spacebar prefabs instantiate from a totally different position away from the player. How do I fix this ?

    My PlayerController script

    public class PlayerController : MonoBehaviour
    {


    public GameObject prefabProjectile; //Linked to prefab object on the inspector


    void Update()
    {

    if (Input.GetKeyDown(KeyCode.Space))
    {
    Instantiate(prefabProjectile, transform.position, prefabProjectile.transform.rotation);

    }


    }


    }
     
  2. MirceaI

    MirceaI

    Unity Technologies

    Joined:
    Nov 24, 2020
    Posts:
    35
    Hello,

    Your code seems correct - if the player is in the root of the scene the new Prefab Instance should be at the same position. If this is not the case it might be a prefabProjectile model issue - if it's not centered to (0, 0, 0) it will look at some random position even if its transform.position is the same as player.tranform.position or the prefabProjectile might have a script that changes its position.

    One test you can try to verify if the spawn position is wrong or something else is wrong is to create a new 3D Object->Sphere, make it a Prefab and try to instantiate the Sphere.

    Best regards,
    Mircea