- Home /
How To Spawn GameObject In Top-Left Corner In 3D Space?
Hey, I'm new to 3D development in Unity and I want to spawn a Game Object in the top left corner of the screen no matter the size and aspect ratio. I tried looking it up on youtube but nothing seemed to work. So, how do I exactly get the screen boundaries in my 3D space on the camera view?
Thanks for any answers in advance :)
Answer by TheTrueDuck · 3 days ago
Hi! You probably want to use Camera.ScreenToWorldPoint() to do this.
Important to notice is that the z-position of the vector you feed it is quite relevant, namely it is the distance from the camera where you want to get the world point. (Has to be done this way, because there are an infinite number of planes where the point would look like it is in the top left to the camera).
If this z-position is zero, it will just be placed at the same position as the camera and probably be clipped away.
This snippet should spawn a cube at the top left position of your MainCamera:
private void Start()
{
float distanceFromCamera = 5;
Vector3 topLeftWorldPoint = Camera.main.ScreenToWorldPoint(new Vector3(0, Camera.main.pixelHeight, distanceFromCamera));
GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube.transform.position = topLeftWorldPoint;
}
The boundaries of the camera are gotten via the Camera.pixelWidth and .pixelHeight values.
You should just be able to switch the cube with whatever gameobject you want. Worth considering is that you will probably want to give it a position offset, either in code or with a parent gameobject.
Hope this helps! :)
Your answer
![](https://koobas.hobune.stream/wayback/20220613061549im_/https://answers.unity.com/themes/thub/images/avi.jpg)