- Home /
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.
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!
Answer by robertbu · Aug 31, 2014 at 03:59 AM
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.
Thanks @robertbu I think I had a suggestion a few weeks ago from someone that I attach an empty game object to help with positioning. Is this a pretty common practice then in Unity? Like a de facto standard to solve this kind of problem? I can do this to align this but I'd still really like to find out what it is I'm missing about positioning in screen space that is keeping me from getting this to line up correctly without this workaround.
Empty game objects are frequently used for this kind of thing. If something is modeled, it is a bit better to put the pivot in the 'right' place, but a empty game object can usually solve this problem.