Search code examples
c#unity-game-enginegame-development

How do I instantiate a prefab in the middle of the screen?


My game requires a prefab to be instantiated in the middle of the screen. Currently I have the code set up like this:

 Instantiate(_Confirm,new Vector3(Screen.width/2,Screen.height/2,0),Quaternion.identity);

However, when I run the code, I find that it object has been instantiated far away from my viewport.

EDIT: It's a 2D game


Solution

  • This should work:

    Vector2 spawnPos = Camera.main.ViewportToWorldPoint(new Vector2(0.5f, 0.5f));
    Instantiate(_Confirm, spawnPos, Quaternion.identity);