Help aligning instantiated prefab in the world view

I have a prefab that I’m dynamically instantiating. When I do it asks for a Vector3. I had been struggling with how to position it correctly using pixel offsets but following some advice I received here I have been able to learn how the screen to world points is supposed to work and the “screen” coordinate system in general.

However, although getting my prefab centered works fine and seems to make sense, when I use what I know about centering it to try and place it flush with the top of the screen I have some unexpected results. The prefab is the rectangular box near the top of the screen shown in this image below.

[31796-not+flush.jpg|31796]

Here is the code I’m using.

int worldUnits = 100;

Instantiate(teamView, Camera.main.ScreenToWorldPoint(new Vector3((Screen.width / 2), (Screen.height) - ((teamView.renderer.bounds.size.y * worldUnits) / 2), gameObject.layer)), Quaternion.identity);

Appreciate any help!

It is easiest to get a world object placed correctly if you setup your anchor correctly. For this, I would place an empty game object centered horizontally and right at the top of the prefab. Then I’d make the visible game object a child of the empty game object. By doing this you’ve essentially change the pivot point from wherever it was placed (usually the center) to the middle top. Then to place it you can just do:

  instantiatedPrefab.transform.position = Camera.main.ViewportToWorldPoint(new Vector3(0.5f, 1.0f, depth));

Where ‘depth’ is the distance you want the prefab away from the camera plane.