Home > Software design >  How do I instantiate a prefab in the middle of the screen?
How do I instantiate a prefab in the middle of the screen?

Time:07-27

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

CodePudding user response:

This should work:

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