Recently I needed very granular control over 2D elements for Unity that needed to be workable in a consistent 1:1 pixel environment. Normally I’d leverage NGUI, 2DToolKit or whatever else I have lying around or is currently present in a project but I decided I didn’t need a sledgehammer to solve this particular challenge so I decided to develop a simple solution for using pixel coordinates and scale in Unity.
To use PixelCamera simply drop it on to your intended rendering camera and let it do the work. Out of the box, PixelCamera will configure things so world space, as rendered by the target camera, translates Unity’s coordinate system to match screen-based pixel coordinates with the exception that y needs to be negative and larger z positioning sets stacking order behind lower values as it pushes objects further from the camera. In addition if your object’s scale matches Unity’s units of measurement you can use the scale of your object to match pixel dimensions. However, most of the time, you would want to move your 2D content away from world center so you can have clean organization of 3D and 2D elements and PixelCamera allows for this style of organization with ease. Simply dump your 2D content into the “Content” child GameObject PixelCamera has generated on the target camera and turn off the “Calculate Position” property. This setup allows any content you put into the Content holder to still be easily placed by pixel coordinates, meaning a transform position of 10, 10, 0 will place an object on the screen 10 pixels from the top and left edge of the screen but now you can move your camera away from world center.
I’ve also included 2 simple components that allow screen anchoring to the typical 9 screen positions (upper left, upper middle, etc…) with manual margin setting as well as screen stretching (stretch width, stretch height, stretch both) for easy screen fills. See these script’s comments for additional details.
An example scene has been included which has some convenient prefabs to help with easily creating pixel perfect work in Unity without a massive framework and hopefully this will help you solve some 2D challenges or become the backbone for your own custom ui solution.
As always, ask questions and offer suggestions.Download